As is expected,
ileaves scope as soon as the loop ends.
jalso leaves scope as soon as the loop ends. So what is the argument behind this behavior from the Visual Basic 2005 Language Enhancements chat? "This behaves the way that Visual Basic has always behaved."
I thought that there were two purposes behind the move from Visual Basic 6 to Visual Basic .NET. The first was fewer bugs through things like guaranteed zeroing of variables, improved object management, and guaranteed object disposal due to the garbage collector. The second was that there were going to be breaking changes in the language, so it was best to make all of them all at once.
I love Visual Basic because the language is essentially a common-sense language. You can look at a piece of code and know what it does. The code above looks like it makes a new
jvariable on each loop, but it doesn't.
As far as creating temporary variables inside of a loop, there are times when that makes sense. While performance may be increased by moving the allocation outside of the loop, there are also times where it is desirable to create variables at the beginning of the scope that they will be used in. That's why we got the
For i As [Type]construct.
Fact is, I don't care what you do under the hood. If you allocate the memory ahead of time, that's fine...but the emitted code should function in a common-sense way. If a developer looks at the code and says that it appears like a new
jis being created each loop, the end result should act like a new
jis being created. That could mean you create and destroy the
j, or it could mean you create
jahead of time, and just emit an MSIL instruction to zero it out at the point where the declaration is made.
You're already recognizing when it leaves scope...you may as well do the same for when it enters scope.