Scope

Scope refers to the so-called visibility of identifiers within source code. That is, given a particular identifier declaration, the scope of the identifier determines where it is legal to reference that identifier in code. For example, these two functions each declare a variable CoffeeBreaks. Each declaration is invisible to the code in the other method. The scope of each variable is the method in which it is declared.

Public Sub MyFirstMethod(  )
   Dim CoffeeBreaks As Integer
   ' ...
End Sub
 
Public Sub MySecondMethod(  )
   Dim CoffeeBreaks As Long
   ' ...
End Sub

Unlike previous versions of Visual Basic, Visual Basic .NET has block scope . Variables declared within a set of statements ending with End, Loop, or Next are local to that block. For example:

Dim i As Integer
For i = 1 To 100
   Dim j As Integer
   For j = 1 To 100
      ' ...
   Next
Next
' j is not visible here

Visual Basic .NET doesn’t permit the same variable name to be declared at both the method level and the block level. Further, the life of the block-level variable is equal to the life of the method. This means that if the block is re-entered, the variable may contain an old value (don’t count on this behavior, as it is not guaranteed and is the kind of thing that might change in future versions of Visual Basic).

Get Programming Visual Basic .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.