How To Do It - Shared Class Variables Part III
For you consideration, this is a discussion
of shared methods, the use of properties, and
other implications for shared variables in
classes. These is the third of four parts
of the How To. Part IV will follow soon.
Private Shared mlngValue As Long = 6
Private mlngNonShared As Long
' NOTE 1
Property lngValue() As Long
lngValue = mlngValue
mlngValue = value
Public Shared Function GetTheValue() As Long
Public Shared Function GetNonSharedValue() As Long
' NOTE 2
' Return mlngNonShared
' NOTE 3
Public Function GetShared() As Long
Public Function AnotherGetNonShared() As Long
' NOTE 4
Public Sub New(ByVal lngArgvValue As Long)
mlngNonShared = lngArgvValue
' NOTE 5
' WriteLine("Value = " & clsTestShare.lngValue.ToString())
' NOTE 6
WriteLine("Value = " & clsTestShare.GetTheValue.ToString())
' NOTE 7
Dim PatsClass As New clsTestShare(9)
' NOTE 8
WriteLine("Value = " & PatsClass.lngValue.ToString())
' NOTE 9
WriteLine("Value = " & PatsClass.GetTheValue.ToString())
' NOTE 10
WriteLine("Value = " & PatsClass.AnotherGetNonShared.ToString())
Properties can not be shared. Therefore they only work for an
Shared methods can only access shared variables of the class.
Normal (nonshared) methods can acess both shared and nonshared
variables of the class. This is because the method exists within
the context of the instatiated object therefore any nonshared
variables of the class also exist.
In this example, the constructor is a nonshared method so it can
access any variable shared or nonshared. Please note that the
constructor can also be a shared method but that's the discussion
for Part IV.
See Kathleen, I did finally get closer to discussing shared
Send lngValue is a property of the class, it is not accessible
through the class name definition rather it can only be used
with an instantiated object of the class.
GetTheValue is a shared method therefore is accessible via the class
Instantiate a instance of the class and pass an initialization value
to the constructor (nonshared NEW method in this example). At this
point I can access any shared or nonshared method of the class using
the instantiated object. I can also access any property of instantiated
object. Finally, I can access and pubic or public shared variable of
the class. Variable reference was covered in Part I of my How To for
shared class variables.
Property is available through the instantiated object.
Shared method is available through the instantiated object.
Nonshared method is available through the instantiated object.
Output from this program is as follows:
Value = 6
Value = 6
Value = 6
Value = 9
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center