In Visual Basic, variables inside procedures typically lose their value after the procedure call ends. The Static keyword allows a variable to preserve its value across procedure calls.
Background:
In classic Visual Basic (VB6) and VB.NET, Static was often used to create counters and flags without using class or module fields.
Problem:
A developer may use regular local variables, assuming their "stability," when they reset with each call. On the other hand, the chosen location (procedure body or code block) for a static variable may be erroneous.
Solution:
Declare a variable using Static inside the procedure. It initializes once during the first call of the procedure, then retains its value between calls.
Code example:
Sub CountCalls() Static counter As Integer = 0 counter += 1 Console.WriteLine($"Call number: {counter}") End Sub ' Calls will generate different values CountCalls() ' 1 CountCalls() ' 2 CountCalls() ' 3
Key features:
Static variable exists only within the procedure's scope but retains its value between calls.What is the difference between Static in a procedure and a class field with the Shared modifier?
A Static variable acts only in the given procedure—each instance of the method gets its independent static variable. A Shared class field is one for the entire class.
Can you declare a Static variable in a For or If block?
No, Static variables are declared only at the top level of the procedure and cannot be inside nested blocks (For, If).
What happens if a procedure with Static is called from multiple threads?
In VB.NET, the scope of Static variables is tied to each thread, which can lead to race conditions and unexpected values when called multithreaded.
In a procedure for calculating user reaction time to a key press, Static is used to store the trigger time, but concurrent key presses by multiple users are not considered (e.g., web application or multithreaded window).
Pros:
Cons:
Static is used for storing an internal call counter for a utility method called only synchronously from one thread.
Pros:
Cons: