VB.NET For the scope of loop functions and block volume

Given the code sample below, it seems that the currOn variable occurs outside the loop and only an instance once. For example, let's say that there are three elements in itemList , and at the second iteration, SomeFunctionThatDoesSomeStuff returns true . Then the value of currOn will be true . At the third iteration, I would think that this VB.NET is the language of the block region, which currOn will be re-created and defaults to false ; however, I see that it remains true and therefore, regardless of the value of sOn , it is not updated in further iterations. This is similar to the javascript function area where the currOn will be currOn out of the loop. Does anyone know what is going on here?

  For Each item As MyItem In itemList Dim currOn As Boolean Dim sOn As Boolean = SomeFunctionThatDoesStuff(item) currOn = currOn OrElse sOn Debug.Print(String.Format("the value of currOn is: {0}", currOn)) Next 

As another example, setting currOn = false explicitly for each iteration works the way I expected it to work.

  For Each item As MyItem In itemList Dim currOn As Boolean = False Dim sOn As Boolean = SomeFunctionThatDoesStuff() currOn = currOn OrElse sOn Debug.Print(String.Format("the value of currOn is: {0}", currOn)) Next 
+6
source share
1 answer

When you declare a variable in a For loop, you declare it within the scope of the block. Objects that were declared inside the block will be available only in this block, but will have a lifetime throughout the procedure.

From MSDN:

Even if the volume of the variable is limited by the block, its lifetime is still dependent on the whole procedure. If you enter a block more than once during a procedure, each block variable retains its previous value. To avoid unexpected results in this case, it is advisable to initialize the block variables at the beginning of the block.

MSDN link: https://msdn.microsoft.com/en-us/library/1t0wsc67.aspx

+5
source

All Articles