Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual Basic
Keywords
P-Z Keywords
 Static

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Basic Language Reference 
Static (Visual Basic) 

Specifies that one or more declared local variables are to remain in existence 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 terminates. A static variable remains in existence 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 you assigned to it. A static variable continues to exist for the lifetime of the class or module in which it is defined.

Rules

  • Declaration Context. You can use Static only on local variables. This means the declaration context for a Static variable must be a procedure or a block within a procedure, and it cannot be a source file, namespace, class, structure, or module.

    You cannot use Static inside a structure procedure.

  • Combined Modifiers. You cannot specify Static together with ReadOnly, Shadows, or Shared in the same declaration.

Behavior

The behavior of any local variable depends on whether it is declared in a Shared procedure. If the procedure is Shared, all its local variables are automatically shared, including the Static variables. There is only one copy of such a variable for the entire application. You call a Shared procedure using the class name, not a variable pointing to an instance of the class.

If the procedure is not Shared, its local variables are instance variables, including the Static variables. There is an independent copy of each variable in each instance of the class. You call a nonshared procedure using a variable pointing to a specific instance of the class. Any variable in that instance is independent of a variable with the same name in another instance. Therefore, they can hold different values.

The following example demonstrates the use of Static.

Visual Basic
Function updateSales(ByVal thisSale As Decimal) As Decimal
    Static totalSales As Decimal = 0
    totalSales += thisSale
    Return totalSales
End Function

The Static variable totalSales is initialized to 0 only once. Each time you enter updateSales, totalSales still has the most recent value you calculated for it.

The Static modifier can be used in this context:

Dim Statement (Visual Basic)

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker