understanding Static variables in VB

Posted Fri, Aug 18 2006 23:00 by bill
I was just reading Julia Lerman's blog about static variables in VB.  Sadly I think Julia has had it wrong, so let me try to explain.  First let's start with some rules:
  • 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:
Class foo
   Public Sub bar()
      Static i As Int32
      i += 1
      Debug.Print(" i : " &  i )
   End Sub
End Class
Module Module1
   Sub Main()
      Dim f As New foo
      For j As Int32 = 1 To 100
   End Sub
End Module
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.
Filed under:


# more on Static local variables

Saturday, August 19, 2006 10:47 AM by @ Head

In my earlier post, I showed how Static local variables in VB are basically local variables that get...