Variable lifetime and scoping in VB.NET
Posted on October 20, 2007 - Filed Under ASP.NET |
Variables hold values that we process in a program. Depending on the type of data to be stored in a variable, each variable should be properly declared in a program. Proper declarations of variables cover intelligent naming and right data type selection. In VB.Net, there are two very important things to consider in declaring variables. First, you should use the right keyword for the variable and second, you should declare them at the right place. The keyword and place where the variable will be declared determines the variable’s lifetime and scope. Lifetime deals with how long the variable will be able to hold its particular value while scope is about to what extent does the value will be accessible in the different parts of the program.
If the variable will be declared inside a sub procedure or function, there are two possible keywords to be used. The first one is the DIM keyword and the other one is the STATIC keyword. DIM and STATIC variable declaration are local in scope, meaning, their values will only be known to that particular procedure only. They differ in lifetime because variables with DIM declaration will no longer hold the value once the execution of the procedure is finished while STATIC declaration will enable the variable to maintain its last value even it goes out of the procedure where it is used.
A form in VB.Net is considered to be a module. If you want to declare a variable with a value intended to be used by all procedure and functions in a module then the PRIVATE keyword should be used. Declare the PRIVATE variables above all the procedures in a module. This type of variable will maintain its value as long as the form or module is loaded and its scope is modular. It is oftentimes referred to as a modular level variable.
If you want to declare a variable intended to be used for the entire Visual Basic project then use the keyword FRIEND and declare it in a formless module (add a module to the project). Lifetime and scoping of this variable is at the project level.
The last one is the PUBLIC variable declaration. The lifetime and scoping of this variable is at the Solution Level. It uses the keyword PUBLIC and is being declared also in a formless module where the Sub Main() function is also placed.
So remember, in declaring variables in VB.NET always keep in mind to use the right keyword and put them at the right place in your program.
Comments
Leave a Reply