variable declared within a loop maintains value through each iteration of the loop

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?

Jon Skeet
people
quotationmark

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.)

people

See more on this question at Stackoverflow