Subtle Bug: VB.Net Dim Statement

Question: What will the following print?

Dim b as Boolean

Console.WriteLine(b.ToString)

If you try it for yourself, you’ll see that the answer is ‘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.

and for Boolean, the default value is False.

But you knew that already, didn’t you?

So, try this one.

Question: What will this do?

         For i As Integer = 1 To 5
            Dim b As Boolean
            Console.WriteLine(b.ToString)
            b = True
        Next

Curiously the answer is not:

False

False

False

False

False

If you try it, you’ll find it prints:

False

True

True

True

True

I’d love to understand exactly why it does this.

Advertisements

3 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.

  3. Yash says:

    For i As Integer = 1 To 5
    Dim b As Boolean
    Console.WriteLine(b.ToString)
    b = True
    Next

    The above code block seems nothing more than lame programming.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: