Understanding Scope in Visual Basic .NET - dummies

By Richard Mansfield

VB.NET programs are subdivided into zones, just as the United States is divided into states, counties, and cities. Just as law enforcement agents have different sizes of jurisdictions (city cops, state troopers, and FBI, which can go anywhere), VB.NET lines of programming have ranges of influence. This range of influence, called scope, applies mostly to variables (but can also apply to procedures — subs and functions — as well as entire classes).

Accessing a variable

Often you want to query or change the value in a variable, but whether or not that variable is accessible to you depends on its scope. For example, you can always access a variable from within the same procedure (functions, subroutines, and events are all procedures).

To see how this works, type the following into your code module:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim N As String = “This”
End Sub

Press F5 and notice that the MsgBox has no problem displaying the value of the variable N.

It displays This. Now type another sub just below the Form1_Load sub in the code window:

Public Sub TryIt()
End Sub

Notice that there is a sawtooth line under the variable N in the TryIt sub. Hold your mouse pointer on top of the sawtooth line and VB.NET displays an error message telling you that Name ‘N’ is not declared.

This error message means that any lines of code within the TryIt sub (between Public Sub and End Sub) cannot read (access) or write (change) the variable N. N was declared (with the Dim command) in a separate procedure, and so the scope of N (its range of accessibility) is limited to lines of code within its same procedure.

Although Dim is the most commonly used, you can use seven additional declaration commands: Static, Public, Protected, Friend, Shared, Protected Friend, and Private. These additional commands specify scope (from which locations in your program a variable can be accessed).

Note that when you declare a variable inside a procedure, the variable works only within that procedure. When the program executes the procedure (or event), the variable comes to life, does its thing, and then dies (disappears) as soon as the End Sub line is executed.

When variables are local

Variables that live only within a single procedure are called local variables. Local variables have two qualities that you need to memorize:

  • No programming outside their own procedure can interact with them, either to read their value or to change their value. Their scope is limited to their own procedure.
  • When VB finishes executing the procedure in which they reside, their value evaporates. If that procedure is executed a second time, whatever value the local variable once contained is no longer there. One execution of the procedure is their lifetime.
    There are some situations in which you do want a local variable’s value to be preserved. In those cases, you use the Static command rather than the Dim command:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim n As Integer

Static x As Integer

End Sub

In this example, the variable n loses its value when the End Sub is executed. However, the variable x retains its value until the program is shut down. Another way of putting it is this: When you use the Static command with a local variable, the value of that variable is preserved for the lifetime of your application. (Lifetime means how long something is in existence in a program.)

What do you think would happen if you put two Command Buttons on your Form, and then you ran the program and clicked Command1 first, and then clicked Command2, in this next program?

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim X As Integer
X = 12
X = X + 5
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim X As Integer
End Sub

The message box displays nothing. The variable X in Command1’s Click event is a completely different variable from the X in Command2’s Click event. They are local in scope and simply have no relationship to each other, no more than two strangers named Mike who happen to live in the Bronx and never meet.

But what if you want both of these procedures to be able to access and manipulate the same variable? To do this, you define the variable outside your procedures. Try it. Click just above your first procedure (just above the line Private Sub Form1_Load) in the code window to move the insertion cursor there.

Now type the following:

Dim x As Integer

That’s where you want to put any variables that you want to give form-wide scope — in other words, to permit all the procedures in that form (Form1, in this case) to be able to read and modify the variable. (The area where you put form-wide variables used to be called the General Declarations area, prior to VB.NET.)

Now, with that X variable Dimmed up there above (outside) all the Subs and other procedures, when you run the same program, click Command1, and then click Command2, you see the result you want to see: the number 17. When you declare X to be form-wide in scope, the two buttons can access that variable X. Delete the two Dim statements that previously declared X within those two Button events. Now X = X + 5 and MsgBox(X) both refer to the same variable named X.

When a variable has form-wide scope, it’s then available to all of the procedures in that form. It’s not available, however, to the procedures in any other forms in the project.