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