开发者

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 V开发者_JAVA技巧B.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.


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.


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


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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜