Tricky Scope (VB.NET)#
Pop quiz: what do you think would be the output of the following code?
Dim i As Integer
For i = 0 To 4
    Dim s As String
    s = s & "X"
    Console.WriteLine(s)
Next
Quite possibly, you would expect to see 5 lines each containing a single X, since the variable is restricted to its scope: the For block. Since it cannot be used outside the block, you would expect it to be reinitialized each time the block is executed. Unfortunately, what we actually get is
X
XX
XXX
XXXX
XXXXX
This is because although the scope of the variable s is limited to the For block (which means it cannot be used outside it), the variable actually starts to exist at the start of the method. It's only initialized to its default value once, upon entry into the method. See Local Variables and Local Declaration Statements in the Visual Basic .NET Language Specification for more information on this.

This means you have to explicitly initialize the variable to Nothing (or to your own default value):
Dim i As Integer
For i = 0 To 4
    Dim s As String = Nothing
    s = s & "X"
    Console.WriteLine(s)
Next
If you would try something similar in C#, the compiler will stop with an error (not a warning): "Use of unassigned local variable 's'" which makes it impossible to make mistakes about this.
Blog | Programming | .NET | Quirks
Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In