I just came across a “feature” of VB that I was unaware of. I’m now a little bit scared of how many bugs I’ve written because I was unaware and ignored the compiler warning to initialize all variables.
Here is some example code.
Public Shared Sub VisibleLifetime()
For i As Integer = 0 To 5
Dim x As Integer
Console.WriteLine(x)
x += 2
Next
End Sub
For some reason I thought, since we declare x within the for loop and the scope of x is confined to the for loop and dot net initializes integers to zero, that x was initialized within the for loop to zero on every iteration. It turns out I’m wrong.
http://blogs.msdn.com/vbteam/archive/2007/06/15/closures-in-vb-part-4-variable-lifetime.aspx
0 comments:
Post a Comment