Home > other >  Local String-variable initialization in Loop
Local String-variable initialization in Loop

Time:11-10

I'm facing a strange behavior with vb.net (framework 4.8,VS2019, Option Explicit and Strict On) and a string variable inside a For Each loop.

Why the tmpVal variable is not reinitialized on each loop, or may I've missed something?

Here is my code :

Sub Main()
    Dim Props() As String = {"one", "two", "three"}
    For Each cProp As String In Props
        Dim tmpVal As String
        If cProp = "two" Then
            If String.IsNullOrEmpty(tmpVal) Then
                tmpVal = cProp
            Else
                tmpVal = "Nope"
            End If
        End If
        Console.WriteLine("cProp " & cProp & " : " & tmpVal)
    Next
    Console.ReadKey()
End Sub

and the output I get :

cProp one :
cProp two : two
cProp three : two

I was expecting the third row to be "empty"

Thank you

CodePudding user response:

Declaring a variable inside a loop does not mean it will be initialized on each iteration.
It just limits the scope to the loop.

Means it will be initialized once to Nothing in your example.

You can change the initialization as follows to get the expected result:

Dim tmpVal As String = ""
  • Related