understanding Static variables in VB
Fri, Aug 18 2006 23:00
- static variables can be used only inside methods. This includes Properties, Subs and Functions.
- the method can be instance method Or Shared
- the method can be in a class or module
Okay, with the rules out of the way, we still haven't said what declaring a variable as static does. What it does is: (my definition)
Declaring a static variable promotes the variable declaration to a field in the containing class or module. This allows persistence of values across method calls, while keeping the variable appearing to be encapsulated within the method.
The following example highlights this behavior:
Public Sub bar()
Static i As Int32
i += 1
Debug.Print(" i : " & i )
Dim f As New foo
For j As Int32 = 1 To 100
You will see the output is along something like:
i : 1
i : 2
i : 3
i : 4
i : 5
i : 6
i : 7
all the way up to 100
So by declaring I as a static variable we have promoted it to a field, yet maintained encapsulation as it can only be accessed inside the method bar where it was declared.
-UPDATE- I forgot to mention about what happen with Shared and instance methods:
One thing to note is the static variable when promoted to a field is declared with the same lifetime as the contianing method. that is, if the method was declared as Shared, the promoted field will have Shared lifetime, otherwise it will be an instance field.