Static Variables

Using Static Variables

Static variables can solve many problems that otherwise look difficult, or may require a global variable.

A static variable is a variable that retains its current  value between invocations of the method within which it is declared.

A variable that is declared within a method (a Sub or a  Function) goes out of scope when that method terminates.  Usually, that  means the variable value is discarded, and a new variable is created and  initialized when the method is next called.  Static variables go out of  scope when the method terminates, but their value is retained, and they are not  re-initialized when the method is next called: they retain the value as   last set.

A static variable is defined like this:

Static CallCount as Integer = 0

Note that an initialization value is still included (this is  good practice for all variable declarations) but the variable will be  initialized to zero only when the method is first called.  The method might  look like this:

 Private Sub myFunction(TestVal as Integer)
   Static CallCount as Integer = 0
   CallCount += 1
   MessageBox.Show("This function has now been called " & CallCount.ToString & " times.")
   '...
 End Sub

Any type of variable can be declared as Static, and any  operation that can be carried out on a variable can be carried out on a Static  variable.  However, static variables are typically only used within the  method where they are declared: exposing static variables to other methods – for  instance, passing them as parameters to other methods – can create logic errors  that are hard to track down.

A Static variable can only have the scope of the method in  which it is defined – a scope modifier cannot be applied to the declaration of a  static variable.

Note: There are parts of the documentation  on MSDN that assert that Visual Basic .Net does not support Static variables and  that Static variables cannot be declared.  This is incorrect and should be  ignored.  It might be a result of confusing the VB .Net Static variable  with the Static keyword that is used in C#, which is a different concept.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s