tags:

views:

99

answers:

2

What does Static mean in VB?

EDIT - Code sample for reference

Module Module1

    Sub Main()
        Dim a = New Foo
        Dim b = New Foo
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(b.Boom)
    End Sub

End Module


Class Foo
    Function Boom() As Integer
        Static callCount As Integer = 0
        callCount += 1
        Return callCount
    End Function
End Class
+4  A: 

It's a way of having fields that are local to a method. Basically, the value is maintained between calls but not accessible in other parts of the class. See Static Local Variables in VB.NET for some implementation information.

EDIT: Jonathan, you're right that the fields don't have to be Shared/static. If the function/sub is declared Shared, it will be a Shared/static field. Otherwise, it will be a instance field. Either way, it is persistent across calls and local to the method. The below example (to continue a theme) shows both behaviors clearly:

Class Fibonacci

    Public Function FibonacciInstance() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Public Shared Function FibonacciShared() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Shared Sub Main()
        Dim d as Integer
        Dim a = New Fibonacci
        Dim b = New Fibonacci       
        For d = 0 to 10
            System.Console.WriteLine("a.FibonacciInstance: " & a.FibonacciInstance())
            System.Console.WriteLine("b.FibonacciInstance: " & b.FibonacciInstance())
            System.Console.WriteLine("a.FibonacciShared: " & a.FibonacciShared())
            System.Console.WriteLine("b.FibonacciShared: " & b.FibonacciShared())
        Next d
    End Sub

End Class
Matthew Flaschen
+1 but give code examples please.
Dario
Nope. I just checked and it definitely doesn't act like a shared field. If I run the code in my editted question, I get "1, 2, 3, 1".
Jonathan Allen
A: 

Explanation in the manual seems pretty clear to me?

http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx

MarkJ