0 Comments

Creating strings inside loops in VB.NET can cause subtle and easy-to-miss bugs. Here’s a simple example:

    Sub Main()

        For i As Integer = 1 To 4 Step 1

            Dim text As String
            text = text & i.ToString

            Console.WriteLine(text)

        Next

        Console.ReadLine()

    End Sub

As we are creating the textvariable inside the for loop, one would presume that this would ouput:

1

2

3

4

Instead, when run, we get this:

image

Check the compiler warnings and you’ll see:

Variable 'text' is used before it has been assigned a value. A null reference exception could result at runtime.

The problem can be easily fixed by assigning an empty value to text when it is declared:

image

Still, this can cause interesting issues if you don’t play close attention to compiler warnings.

Post comment