Variable Scope

Variable Scope

The Scope or Accessibility of a variable depends on where it can be called in an application, and what the lifetime in memory the variable has. This also determines what context the method can be called. The following are defining terms for scope variables.

Scope Terms

Public: Anywhere in or outside of a project

Private: Only in the block where defined

Protected: Can be used in the class where defined. Can also be used within any inherited classes.

Friend: Can only be accessed in code in the same project or assembly
ProtectedFriend: Combination of Protected and Friend

Scope Rules
There are four levels that variables can be declared in an application.

1.Block:  i.e. within an if statement, the variable lifetime ends at the end of the block

2.Procedure: i.e. within a method, outside of an if statement

3.Class: i.e. within a class the lifetime ends when the object is cleaned by the garbage collector

4.Project: i.e. Public variables within module statements, lifetime is until the program ends

Procedure Modifiers

Public: Can be called from anywhere in a project

Private: Can only be called within the class it is declared
Protected: Can only be in the same class from the same class or inherited classes

Friend: Can be called from any code in the same project or assembly

ProtectedFriend: Can be called from in its defined, derived, or procedures in the same project/assembly

Static Variables

Shadowing

Reference: http://msdn.microsoft.com/en-us/library/ms973875.aspx

Author: Travis Gneiting

Passionate Professional .NET Developer