Chapter 13. Understanding Scope

A variable's scope is the code that can "see" or access that variable. It determines whether a piece of code can read the variable's value and give it a new value.

In this lesson you learn what scope is; why restricting scope is a good thing; and how to determine a variable's scope.

SCOPE WITHIN A CLASS

A Visual Basic class (and note that Form types are classes, too) contains three main kinds of scope: class scope, method scope, and block scope. (If you have trouble remembering what a class is, review Lesson 9's section "Understanding Classes and Instances.")

  • Variables with class scope are declared inside the class but outside of any of its methods. (A method is a routine containing statements, such as an event handler or a subroutine that you write.) These variables are visible to all of the code throughout the instance of the class and are known as fields.

  • Variables with method scope are declared within a method. They are usable by all of the code that follows the declaration within that method.

  • Variables with block scope are declared inside a block of code defined by some other program element such as an If Then statement or a For loop. The section "Block Scope" later in this lesson says more about this.

For example, consider the following code that defines a field, and some variables inside event handlers:

Public Class Form1
    ' A field.
    Dim a As Integer = 1
Private Sub btnClickMe_Click() Handles btnClickMe.Click ' A method variable. Dim b As Integer = 2 ...

Get Stephens' Visual Basic® Programming 24-Hour Trainer 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.