Also known as a Class Field.
A class variable defined with a specific class visibility, usually private visibility. A member property is different than a member field. A member property uses a member field to store values through accessor methods (getters and setters). For example, it is common to use a private member field to store the current value of a property. The current values of all the class member fields is the current state of the object.
Languages Focus: Member Field
What modifiers apply to member fields, if any? Typical member field modifiers include scope modifiers (private, protected, etc.) and read-only. Can you initialize the value of a member field when declared ensuring a default value?
VB.Net Member Field
In VB.Net you can set the visibility of a member field to any visibility: private, protected, public, friend or protected friend.
You can intialize a member field with a default when declared. If you set the member field value in your constructor, it will override the default value.
Finally, you can use the Shared modifier (no instance required) and ReadOnly modifier (similar to a constant).
Syntax Example: Public Class Cyborg
Private FSerialNumber As String = "A100"
Public CyborgName As String
Public CyborgAge As Integer
Public Shared ReadOnly SeriesID As Integer = 100
End Class
A Simple Example
The following example uses our class above. Notice for the static member, we do not use a variable, instead we use the class name directly. That's why static members are sometimes referred to as class members. Static members belong to the class and are referenced by the class name.
Note: The public member fields CyborgName and CyborgAge are used here for demonstration only. You normally want to make them private and access them via a member property.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Read static member field BEFORE we create our object.
'Notice the use of the class name, not an object name.
MessageBox.Show("We will now build a series " & Cyborg.SeriesID & " robot.")
Dim MyRobot As New Cyborg
MyRobot.CyborgName = "John"
MyRobot.CyborgAge = 34
MessageBox.Show("We created a " & MyRobot.CyborgAge & " year old robot named " & MyRobot.CyborgName & ".")
'You should not refer to static members using an instance.
'You will get a compiler warning (in C# you get a compiler error).
'MessageBox.Show("A series " & MyRobot.SeriesID & " robot.")
'Use a type name instead.
MessageBox.Show("A series " & Cyborg.SeriesID & " robot.")
End Sub
End Class
Public Class Cyborg
Private FSerialNumber As String = "A100"
Public CyborgName As String
Public CyborgAge As Integer
Public Shared ReadOnly SeriesID As Integer = 100
End Class