Local variables - Those declared within a procedure (subroutine or function) of a class (or other structure). In this example, exampleLocalVariable
is a local variable declared within ExampleFunction()
:
Public Class ExampleClass1
Public Function ExampleFunction() As Integer
Dim exampleLocalVariable As Integer = 3
Return exampleLocalVariable
End Function
End Class
The Static
keyword allows a local variable to be retained and keep its value after termination (where usually, local variables cease to exist when the containing procedure terminates).
In this example, the console is 024
. On each call to ExampleSub()
from Main()
the static variable retains the value it had at the end of the previous call:
Module Module1
Sub Main()
ExampleSub()
ExampleSub()
ExampleSub()
End Sub
Public Sub ExampleSub()
Static exampleStaticLocalVariable As Integer = 0
Console.Write(exampleStaticLocalVariable.ToString)
exampleStaticLocalVariable += 2
End Sub
End Module
Member variables - Declared outside of any procedure, at the class (or other structure) level. They may be instance variables, in which each instance of the containing class has its own distinct copy of that variable, or Shared
variables, which exist as a single variable associated with the class itself, independent of any instance.
Here, ExampleClass2
contains two member variables. Each instance of the ExampleClass2
has an individual ExampleInstanceVariable
which can be accessed via the class reference. The shared variable ExampleSharedVariable
however is accessed using the class name:
Module Module1
Sub Main()
Dim instance1 As ExampleClass4 = New ExampleClass4
instance1.ExampleInstanceVariable = "Foo"
Dim instance2 As ExampleClass4 = New ExampleClass4
instance2.ExampleInstanceVariable = "Bar"
Console.WriteLine(instance1.ExampleInstanceVariable)
Console.WriteLine(instance2.ExampleInstanceVariable)
Console.WriteLine(ExampleClass4.ExampleSharedVariable)
End Sub
Public Class ExampleClass4
Public ExampleInstanceVariable As String
Public Shared ExampleSharedVariable As String = "FizzBuzz"
End Class
End Module