Subtle Bug: VB.Net Dim Statement

Here is a question for you – are the following pieces of code equivalent?

Declaration followed by Explicit Initializer

[sourcecode language="vb"]
Dim b As Boolean
b = False
Console.WriteLine(b.ToString)
[/sourcecode]

Declaration with Implicit Implicit Initializer

[sourcecode language="vb"]
Dim b As Boolean
Console.WriteLine(b.ToString)
[/sourcecode]

If you try them for yourself, you’ll see that they both produce the same result in the console:

False

Why? According to MSDN:

If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type. MSDN

So, VB sets the value of b to False, the default for a boolean type.

But you knew that already, didn’t you?

However, assuming that two pieces of code that produce the same result are exactly equivalent is a mistake.

So, try these two:

Declaration followed by Explicit Initializer, in a Loop

[sourcecode language="vb"]
For i As Integer = 1 To 5
    Dim b As Boolean
    b = False
    Console.WriteLine(b.ToString)
    b = True
Next
[/sourcecode]

Declaration with Implicit Implicit Initializer in a Loop

[sourcecode language="vb"]
For i As Integer = 1 To 5
    Dim b As Boolean
    Console.WriteLine(b.ToString)
    b = True
Next
[/sourcecode]

This time, you’ll find that the two pieces of code produce different results. The first one will print:

False

False

False

False

False

While the second one will print:

False

True

True

True

True

The reason is that, in VB.Net, a Dim is a declaration, not a statement. As such, it is only used to set up the variable on the first pass, and in consequence the default initializer is only invoked on the first pass.

Be Sociable, Share!
This entry was posted in VB.Net and tagged . Bookmark the permalink.

2 Responses to Subtle Bug: VB.Net Dim Statement

  1. Richard Hall says:

    The line
    >Dim b As Boolean
    is only executed once in the loop. The second time thorough the loop the variable exists and is not created and so not initialized.

    Declarations should be moved outside of all loop structures.

  2. kramii says:

    Richard:

    I agree with your description of Dim’s behaviour. Very well explained.

    However, I don’t think that moving the declaration out of the loop is always a good idea, Granted, there may be a performance benefit, but with a modern machine that’s often less important than it used to be. My feeling is that readability can suffer if variable declaration is moved too far from its first use, as might be the case in a loop with a longer body. I prefer to ensure that all my variables have explicit initialization. I only wish that there were a compiler option to enforce this: I have been know to slip up from time to time.

Leave a Reply

Your email address will not be published. Required fields are marked *