Variable Scope
Variable Scope
The scope of a declared element determines where in a program the variable is visible to the code. This can refer to the namespace of the project, the class file, the procedure within the file, and a code block within the procedure.
Block scope
In VB.NET variables may be declared at any point in the program source code. If the variable is declared within the body of a loop statement, then the variable has block-level scope and is not visible to code outside that loop.
If the variable is declared inside a procedure (a VB sub or function) and outside any loop structure, then the variable has procedure-level scope and is visible to code within that procedure only.
Variables declared with block-level scope cannot have the same name as any variable declared procedure-level scope containing that block. That would lead to a name clash and a syntax error. The same variable names can be used within different procedures but they are different variables.
Procedure scope / Module scope / Namespace scope
Within a class or module definition in VB.NET variables should be declared as either Public, Private, Protected, or Friend instead of Dim (which defaults to Private but its use can be unclear). These modifiers cannot be applied to local scope variables.
The Public modifier means the class variable is accessible within all procedures of the class and to external projects that have a reference to this project.
The Private modifier means the class variable is accessible within all procedures of the class only.
The Protected modifier means the class variable is accessible within all procedures of the class and for any classes derived from that class (the child classes); however, objects instantiated in that class do not have access.
The Friend modifier means the class variable is accessible within all procedures of the class and to other classes and modules within the project, and so has namespace-level scope. The Protected Friend modifier confers both friend and protected access to the element so they are accessible anywhere in the same program, from their class, and from derived classes.
Modifier |
visible within class itself? |
visible to derived class? |
visible to objects derived from class? |
Public |
Yes |
Yes |
Yes |
Private |
Yes |
No |
No |
Protected |
Yes |
Yes |
No |
Friend |
Yes |
Yes |
Yes * visible to entire project |
What happens if the same variable name is declared in the class, procedure and block?
Variable Lifetime
The lifetime of a variable is when and for how long a particular variable exists in memory while the program is executing. Lifetime refers to when the variable can be used; scope refers to where in the program it can be used.