VB.Net's Dim [modified]
-
...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence):
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
He intended the result to be:False
False
False
False
FalseWhich is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:
False
True
True
True
True(Try it if you don't believe me!) The solution was to explicitly assign the value of 'b':
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
Result:False
False
False
False
FalseEdit: Corrected the error in the final example, as pointed out by leppie.
modified on Wednesday, September 10, 2008 5:13 AM
-
...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence):
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
He intended the result to be:False
False
False
False
FalseWhich is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:
False
True
True
True
True(Try it if you don't believe me!) The solution was to explicitly assign the value of 'b':
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
Result:False
False
False
False
FalseEdit: Corrected the error in the final example, as pointed out by leppie.
modified on Wednesday, September 10, 2008 5:13 AM
-
Ok something I do not get. The 1st result shows 5 entries, the 2nd 5, and the third 4. Something fishy... (besides the described behavior)
xacc.ide - now with TabsToSpaces support
IronScheme - 1.0 alpha 4a out now (29 May 2008)It probably got so confused about what value it should have that it just gave up.
I still remember having to write your own code in FORTRAN rather than be a cut and paste merchant being pampered by colour coded Intellisense - ahh proper programming - those were the days :)
-
...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence):
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
He intended the result to be:False
False
False
False
FalseWhich is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:
False
True
True
True
True(Try it if you don't believe me!) The solution was to explicitly assign the value of 'b':
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
Result:False
False
False
False
FalseEdit: Corrected the error in the final example, as pointed out by leppie.
modified on Wednesday, September 10, 2008 5:13 AM
When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)
Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]
-
Ok something I do not get. The 1st result shows 5 entries, the 2nd 5, and the third 4. Something fishy... (besides the described behavior)
xacc.ide - now with TabsToSpaces support
IronScheme - 1.0 alpha 4a out now (29 May 2008) -
When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)
Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]
-
Chris Meech wrote:
Probably another case of the documentation not being completely true. Or false.
:laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.
its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.
-
Chris Meech wrote:
Probably another case of the documentation not being completely true. Or false.
:laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.
I think that means you can't set a breakpoint on a line with just a dim statement. At least, that's the way it's always been in VB before.
Imagine that you are hired to build a bridge over a river which gets slightly wider every day; sometimes it shrinks but nobody can predict when. Your client provides no concrete or steel, only timber and cut stone (but they won't tell you what kind). The coefficient of gravity changes randomly from hour to hour, as does the viscosity of air. Your only tools are a hacksaw, a chainsaw, a rubber mallet, and a length of rope. Welcome to my world. -Me explaining my job to an engineer
-
its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.
I quite agree, and have advised my colleague to do so in future. Nevertheless, I was surprised by results of missing out the initialization in this case. IMHO, VB.Net should insist on initialization. Ideally, the compiler would refuse to compile without explicit initialization. Alternatively (to stop legacy code breaking) the IDE could automatically insert the initialization for you, even if the compiler could live without it. Incidentally, there here are a couple of links to related material: Gain performance by not initializing variables[^] VB.NET and variable initialization [^]
-
I quite agree, and have advised my colleague to do so in future. Nevertheless, I was surprised by results of missing out the initialization in this case. IMHO, VB.Net should insist on initialization. Ideally, the compiler would refuse to compile without explicit initialization. Alternatively (to stop legacy code breaking) the IDE could automatically insert the initialization for you, even if the compiler could live without it. Incidentally, there here are a couple of links to related material: Gain performance by not initializing variables[^] VB.NET and variable initialization [^]
KramII wrote:
Gain performance by not initializing variables[^]
Only in .net 1.1. in 2005, explicit constructor initialization is faster. http://www.codeproject.com/script/Forums/View.aspx?fid=182387&msg=1115892[^]
Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall
-
KramII wrote:
Gain performance by not initializing variables[^]
Only in .net 1.1. in 2005, explicit constructor initialization is faster. http://www.codeproject.com/script/Forums/View.aspx?fid=182387&msg=1115892[^]
Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall
-
Chris Meech wrote:
Probably another case of the documentation not being completely true. Or false.
:laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.
What that means is that the Dim statement does not behave like a normal statement. The placement defines the scope of the variable within the procedure, but it is never "executed" as a statement. If you step through the code, you will see that the Dim statement is never executed. FWIW, this behavior occurs in VB6 as well.
Sub Main()
Dim i As Integer
For i = 1 To 5
Dim b As Boolean
Debug.Print b
b = True
Next
End Sub -
When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)
Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]
I guess the default value for POD's - as in C - is "unspecified".
-
...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence):
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
He intended the result to be:False
False
False
False
FalseWhich is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:
False
True
True
True
True(Try it if you don't believe me!) The solution was to explicitly assign the value of 'b':
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
Result:False
False
False
False
FalseEdit: Corrected the error in the final example, as pointed out by leppie.
modified on Wednesday, September 10, 2008 5:13 AM
Shows you shouldn't rely on the compiler to assign 'default' values. I always assign "a value" to my variables... :-D
V.
Stop smoking so you can: Enjoy longer the money you save. Moviereview Archive -
Shows you shouldn't rely on the compiler to assign 'default' values. I always assign "a value" to my variables... :-D
V.
Stop smoking so you can: Enjoy longer the money you save. Moviereview ArchiveV. wrote:
I always assign "a value" to my variables...
Same here. Easier to just to assign a value and saves from having to track down strange results due to compiler defaults being assigned.
"The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham
-
Chris Meech wrote:
Probably another case of the documentation not being completely true. Or false.
:laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.
It simply means you can't set a breakpoint there. It is not translated to any code and in the disassembly you will not find anything corresponding to that line. Initializing the variable does produce code and therefore you can then see it in the disassembly or place a breakpoint there.
A while ago he asked me what he should have printed on my business cards. I said 'Wizard'. I read books which nobody else understand. Then I do something which nobody understands. After that the computer does something which nobody understands. When asked, I say things about the results which nobody understand. But everybody expects miracles from me on a regular basis. Looks to me like the classical definition of a wizard.
-
It simply means you can't set a breakpoint there. It is not translated to any code and in the disassembly you will not find anything corresponding to that line. Initializing the variable does produce code and therefore you can then see it in the disassembly or place a breakpoint there.
A while ago he asked me what he should have printed on my business cards. I said 'Wizard'. I read books which nobody else understand. Then I do something which nobody understands. After that the computer does something which nobody understands. When asked, I say things about the results which nobody understand. But everybody expects miracles from me on a regular basis. Looks to me like the classical definition of a wizard.
-
Chris Meech wrote:
Probably another case of the documentation not being completely true. Or false.
:laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.
The Dim statement causes the variable to be initialized upon creation. However, creation occurs only once. The Dim statement is not executed again on each iteration through the loop therefore it does not reinitialize the variable on each iteration. Bill W
-
...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence):
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
He intended the result to be:False
False
False
False
FalseWhich is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:
False
True
True
True
True(Try it if you don't believe me!) The solution was to explicitly assign the value of 'b':
Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub
Result:False
False
False
False
FalseEdit: Corrected the error in the final example, as pointed out by leppie.
modified on Wednesday, September 10, 2008 5:13 AM
The following is also buggy. Imports System public class Test Public Shared Sub Main() For i As Integer = 1 To 5 Dim b As String if i > 1 then Console.WriteLine(b.SubString(2)) end if Console.WriteLine(b) b = "killer" Next Console.ReadLine() End Sub end class Which normally should cause an null reference exception causes ller to be written out, you can't write the same code in C#, because using an uninitialized variable is an error instead of an warning.
-
its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.
I agree, and I do that on a regular basis but in fact the older version so FxCop (not sure if the new version do this0 tell you that doing that is wasted because the framework takes care of the initialization for you. I had just disable that rule in FxCop but I found it interesting that their tool was telling us to do exactly what decades of CS training and classes have beat into our heads as gospel.