This documentation is archived and is not being maintained.

Variable Scope Changes in Visual Basic

Visual Basic .NET updates local variable scope to support block scope and improve structured programming.

Visual Basic 6.0

In Visual Basic 6.0, any variable declared inside a procedure has procedure scope, so it can be accessed anywhere else within the same procedure. If the variable is declared inside a block — that is, a set of statements terminated by an End, Loop, or Next statement — the variable is still accessible outside the block. The following example illustrates procedure scope:

For I = 1 To 10 
   Dim N As Long 
' N has procedure scope although it was declared within a block. 
   N = N + Incr(I) 
W = Base ^ N 
' N is still visible outside the block it is declared in. 

Visual Basic .NET

In Visual Basic .NET, a variable declared inside a block has block scope, and it is not accessible outside the block. The preceding example can be rewritten as follows:

Dim N As Long = 0 
' N is declared outside the block and has procedure scope. 
For I As Integer = 1 To 10 
   N = N + Incr(I) 
Next I 
W = Base ^ N 
' N is visible outside the block but I is not. 

Because the For statement declares I as part of the For block, I has block scope only.

However, a variable's lifetime is still that of the entire procedure. This is true whether the variable has block scope or procedure scope. If you declare a variable inside a block, and if you enter that block several times during the lifetime of the procedure, you should initialize the variable to avoid unexpected values.

See Also

Choice of Variable Scope | Programming Element Support Changes Summary