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

I tried to find this on the Internet, but my GoogleFu did not help me ...

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

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

+3
source share
3 answers

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

+3
source

It creates a new one FooBarfor each iteration. This is almost the same as:

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

... , FooBar, , While ( ).

+2

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

This statement is not 100% true, though. In VB.Net you can actually see the previous value of a variable with a few tricks. 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 
+1
source

Source: https://habr.com/ru/post/1729417/


All Articles