The second reason for using a Shared member is to ... well ... "share" it. Consider this code that counts the number of times a shared method is called. The variable m_SharedVar keeps it's value because there's only one copy of it.
Public Class Form1
Private Sub FirstCallSharedMethod_Click( ...
PrintResult(SharedMethodClass.SharedMethod)
End Sub
Private Sub SecondSharedMethodCall_Click( ...
PrintResult(SharedMethodClass.SharedMethod)
End Sub
Friend Sub PrintResult(ByRef CurrentCallCount As Integer)
Result.Text += "The shared class has been called " _
& CurrentCallCount.ToString & _
" Time(s)" & vbCrLf
End Sub
End Class
Public Class SharedMethodClass
Shared m_SharedVar As Integer = 0
Shared Function SharedMethod()
m_SharedVar += 1
Return m_SharedVar
End Function
End Class
And again, a snapshot of the code being executed is in the illustration below:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Notice that the variable m_SharedVar is also declared as Shared.
The default declaration of .NET objects is non-shared (dynamic). If you try to declare it as a non-shared variable (with the Dim keyword), you have to move it inside the Function block and, because it's non-shared, it's initialized every time the function is called. So the function always returns the value 1. It's worth keeping in mind that Shared isn't the same thing as Public. The m_SharedVar variable is still Private to the object so it can't be altered by code outside the class. (You can add Private to the declaration and it doesn't change a thing.)
Another variation on this pattern is called a shared constructor. If you code a Shared New method, called a shared constructor, in a class ...
Public Class Form1
Private Sub Form1_Load( ...
Debug.WriteLine(SharedConstructorClass.sharedField)
End Sub
End Class
Class SharedConstructorClass
Public Shared sharedField As String
' shared constructor
Shared Sub New()
sharedField = "Initialized by CLR!!"
End Sub
End Class
... then when the class is used, the constructor is called automatically by the common language runtime (CLR). The code above displays "Initialized by CLR!!" in the Immediate window.
You can use the Shared keyword with
- Dim
- Event
- Function
- Operator
- Property
- Sub
On the next page, we switch from Shared to dynamic.

