|
|
|
Understanding Variable Scope and Duration There are two key attributes of all variables in Visual Basic that are essential to understanding their use:
Variable ScopeThe scope of a variable determines where you can access that variable in your code. If a variable is in scope you can read or set it's value. If it is out of scope you will not be able to access it.There are three types of scope for variables in Visual Basic:
Global ScopeGlobal variables are available anywhere in your program. Any line of code in any procedure can read or write the value of the variable. While convenient, it is considered bad programming practice to overuse global variables and some programmers (myself included) make a considerable effort to avoid them entirely.To create a global variable, declare it in the declarations section of a standard module using the Global or Public keyword. Module ScopeModule level variables are available to any code within the module where they are declared. While using global variables is considered bad programming practice, using module level variables is not. Module level variables allow you to share data between procedures without exposing that data to every procedure in the application.To create a module level variable, declare it in the declarations section of a module using either the Dim or Private keyword. Local ScopeLocal variables are only available to the procedure in which they are created. Local variables are the most restricted in scope - not even other procedures in the same module may read or modify local variables.You create local variables by declaring them with the Dim or Static keyword within the body of a Sub, Function, or Property procedure. VariationsThere are a few variations from the basic scoping rules:
Go To Page: 1 2
The copyright of the article Understanding Variable Scope and Duration in Learning Visual Basic is owned by . Permission to republish Understanding Variable Scope and Duration in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|