Static (Visual Basic)
Updated: July 20, 2015
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
Specifies that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared.
Normally, a local variable in a procedure ceases to exist as soon as the procedure stops. A static variable continues to exist and retains its most recent value. The next time your code calls the procedure, the variable is not reinitialized, and it still holds the latest value that you assigned to it. A static variable continues to exist for the lifetime of the class or module that it is defined in.
Declaration Context. You can use
Staticonly on local variables. This means the declaration context for a
Staticvariable must be a procedure or a block in a procedure, and it cannot be a source file, namespace, class, structure, or module.
You cannot use
Staticinside a structure procedure.
The data types of
Staticlocal variables cannot be inferred. For more information, see Local Type Inference.
Combined Modifiers. You cannot specify
Sharedin the same declaration.
When you declare a static variable in a
Shared procedure, only one copy of the static variable is available for the whole application. You call a
Shared procedure by using the class name, not a variable that points to an instance of the class.
When you declare a static variable in a procedure that isn't
Shared, only one copy of the variable is available for each instance of the class. You call a non-shared procedure by using a variable that points to a specific instance of the class.
The following example demonstrates the use of
Function updateSales(ByVal thisSale As Decimal) As Decimal Static totalSales As Decimal = 0 totalSales += thisSale Return totalSales End Function
totalSales is initialized to 0 only one time. Each time that you enter
totalSales still has the most recent value that you calculated for it.
Static modifier can be used in this context: