In addition to type and scope, variables have a lifetime, which is the period for which they retain their value. Variables declared as Public exist for the lifetime of the application. Local variables, declared within procedures with the Dim or Private statement, live as long as the procedure. When the procedure finishes, the local variables cease to exist, and the allocated memory is returned to the system. Of course, the same procedure can be called again. In this case, the local variables are re-created and initialized again. If a procedure calls another, its local variables retain their values while the called procedure is running.
You also can force a local variable to preserve its value between procedure calls by using the Static keyword. Suppose that the user of your application can enter numeric values at any time. One of the tasks performed by the application is to track the average of the numeric values. Instead of adding all the values each time the user adds a new value and dividing by the count, you can keep a running total with the function RunningAvg(), which is shown in Listing 2.6.
Listing 2.6: Calculations with Global Variables
Function RunningAvg(ByVal newValue As Double) As Double
CurrentTotal = CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
Code language: VB.NET (vbnet)
You must declare the variables CurrentTotal and TotalItems outside the function so that their values are preserved between calls. Alternatively, you can declare them in the function with the Static keyword, as shown in Listing 2.7.
Listing 2.7: Calculations with Local Static Variables
Function RunningAvg(ByVal newValue As Double) As Double
Static CurrentTotal As Double
Static TotalItems As Integer
CurrentTotal = CurrentTotal + newValue
TotalItems = TotalItems + 1
RunningAvg = CurrentTotal / TotalItems
End Function
Code language: VB.NET (vbnet)
The advantage of using static variables is that they help you minimize the number of total variables in the application. All you need is the running average, which the RunningAvg() function provides without making its variables visible to the rest of the application. Therefore, you don’t risk changing the variables’ values from within other procedures.
Variables declared in a module outside any procedure take effect when the form is loaded and cease to exist when the form is unloaded. If the form is loaded again, its variables are initialized as if it’s being loaded for the first time.
Variables are initialized when they’re declared, according to their type. Numeric variables are initialized to zero, string variables are initialized to a blank string, and object variables are initialized to Nothing.