I couldn't work out if this is a bug or a feature
For i = 0 To 4
Dim strTest As String
If i = 0 Then
strTest = "test value"
End If
Console.WriteLine(strTest)
Next
I thought that by declaring the string inside the loop, it wouldn't maintain its value but after running this code the console has 5 lines of "test value". If instead i declare strTest like:
Dim strTest As String= ""
Then the string doesn't maintain its value- which is how i would have expected the function to operate in the first place.
Is this intentional behavior by the compiler?
"Broken as designed"
http://msdn.microsoft.com/en-us/library/1t0wsc67.aspx
Note Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.
The "block" here is the body if the FOR loop, and you are entering it one pr. iteration of the loop. And so strTest will retain the value set in the first iteration ("test value") for the next iterations (1, 2, 3, 4).
It's well specified behaviour. From section 10.9 of the VB 11 specification:
Each time a loop body is entered, a fresh copy is made of all local variables declared in that body, initialized to the previous values of the variables. Any reference to a variable within the loop body will use the most recently made copy.
Note that the fact that it's a "fresh copy" is potentially important if any lambda expressions are used which capture the local variable. From later in the same section:
And when a lambda is created, it remembers whichever copy of a variable was current at the time it was created.
(There's an example which clarifies that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With