Export (0) Print
Expand All

Choice of Variable Scope

Visual Studio .NET 2003

The scope of a variable is the set of all code that can refer to it without qualifying its name. A variable's scope is determined by where the variable is declared.

When considering scope, keep in mind that local variables are a good choice for any kind of temporary calculation. They consume memory only when their procedure is running, and their names are not susceptible to conflict. For example, you can create several different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures.

Note   Module, shared, instance, and static variables consume memory resources until your application stops running, so use them only when necessary.

In general, when declaring any variable or constant, it is good programming practice to make the scope as narrow as possible (block scope is the narrowest). This helps conserve memory and minimizes the chances of your code erroneously referring to the wrong variable. Similarly, you should declare a variable to be Static only when it is necessary to preserve its value between procedure calls.

See Also

Variable Declaration | Scope | Dim Statement | Public | Protected | Friend | Private | Shared | Static

© 2014 Microsoft