Casey Wilkins
Casey Wilkins

Reputation: 2595

How does block level scope work with Dim As New in VB.net?

I tried to find this on the web, but my GoogleFu has failed me...

While DataReader.Read
    Dim Foo as New FooBar
    Foo.Property = "Test"
Loop

In VB.net, does this create a new Foo instance every for every loop? Or just one Foo instance with block level scope? Do all blocks (If..EndIf, For..Next) work the same in this regard? I know that Foo is not accessible outside of the block, just not sure if it creates multiple Foo instances.

Upvotes: 3

Views: 337

Answers (3)

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

It creates a new FooBar for each iteration. It is almost the same as this:

Dim Foo as FooBar
While DataReader.Read
    Foo = New FooBar
    Foo.Property = "Test"
Loop

...with the difference being that the FooBar that is created in the last iteration will be available for code below the While loop (within the same block, that is).

Upvotes: 2

JaredPar
JaredPar

Reputation: 754763

This will create a new Foo for every iteration of the loop.

This statement is not 100% true though. In VB.Net it is actually possible to see the previous value of a variable with a bit of tricker. For example

Dim i = 0
While i < 3
  Dim Foo As FooBar
  if Foo IsNot Nothing
    Console.WriteLine(Foo.Property)
  End If
  Foo = New FooBar()
  Foo.Property = "Test" + i  
  i = i + 1
End While 

Upvotes: 1

Jon
Jon

Reputation: 6046

Since you are in a loop you will get multiple Foo instances. Any foo created inside of a block will not be accessible outside of that block.

Upvotes: 3

Related Questions