DEV Community

Costin Manda
Costin Manda

Posted on • Originally published at siderite.dev on

VB.Net Gotcha: Always assign variables when declaring them

Original post at: https://siderite.dev/blog/vbnet-gotcha-always-assign-variables-when-declarin

Tell me, what will this Visual Basic .NET code display?

For x as Integer = 1 to 2
  Dim b as Boolean
  Console.WriteLine("b is " & b)
  b = true
Next
Enter fullscreen mode Exit fullscreen mode

Even if you never coded in Visual Basic it's a relatively easy code to translate to something like C#:

for (var x = 1; x <= 2; x++)
{
    bool b;
    Console.WriteLine("b is " + b);
    b = true;
}
Enter fullscreen mode Exit fullscreen mode

Now what will the code display? Let's start with this one. This code will not compile and instead you will get: Use of unassigned local variable 'b'.

But what about the VB one? Even with Option Strict ON it will not even warn you. And the output will be: False, True. What?!

In conclusion, VB.Net will let you declare variables without assigning any value to them, but their value will be inconsistent. Always set the variables you declare.

Discussion (0)