1

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

MatSnow
  • 7,357
  • 3
  • 19
  • 31
M0um0utte
  • 13
  • 2
  • You only assign `tempVal` once when `cProp = "two" And String.IsNullOrEmpty(tmpVal)`. Otherwise it's never updated. – Enigmativity Nov 09 '21 at 09:56

1 Answers1

2

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 = ""
MatSnow
  • 7,357
  • 3
  • 19
  • 31
  • 1
    Thank you you're right. the related info at Microsoft if it can help: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/scope – M0um0utte Nov 09 '21 at 10:43
  • I believe the String, being a reference type, is initialized to Nothing. – Mary Nov 09 '21 at 14:15
  • @Mary You're right. I got confused because of this: https://stackoverflow.com/questions/2633166/nothing-string-empty-why-are-these-equal – MatSnow Nov 09 '21 at 15:10