Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET For loop function scope vs block scope

Tags:

scope

vb.net

Given the code sample below, it seems that the variable currOn is raised up outside of the loop and only instantiated once. For example, say there are three items in itemList and on the second iteration SomeFunctionThatDoesSomeStuff returns true. The value of currOn will then be true. On the third iteration, I would have thought that given VB.NET is a block scope language that currOn would be re-instantiated and default to false; however, I see that it remains true and therefore no matter the value of sOn, does not get updated in further iterations. It seems like javascript's function scope where the declaration of currOn would be pulled up outside the loop. Anyone know what's 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 a further example, explicitly setting currOn = false every iteration seems to work as I would have expected the above 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
like image 458
TKTS Avatar asked Sep 16 '15 21:09

TKTS


1 Answers

When declaring a variable within a For loop you are declaring it within a block scope. The objects that have been declared within a block will only be accessible within that block but will have a lifetime across the entire procedure.

From MSDN:

Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.

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

like image 81
вʀaᴎᴅᴏƞ вєнᴎєƞ Avatar answered Sep 28 '22 05:09

вʀaᴎᴅᴏƞ вєнᴎєƞ