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. Also not that cyborgName and cyborgAge start with a lowercase "c" and SeriesID starts with an uppercase "S". The reason I did this is normally you would make use of read-write public member fields. You would make them private. It is common to make member fields lowercase and properities uppercase.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CR_MemberFields
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Read static member field BEFORE we create our object.
//Notice the use of the class name, not a variable.
MessageBox.Show("We will now build a series " + Cyborg.SeriesID + " robot.");
Cyborg MyRobot = new Cyborg();
MyRobot.cyborgName = "John";
MyRobot.cyborgAge = 34;
MessageBox.Show("We created a " + MyRobot.cyborgAge + " year old robot named " + MyRobot.cyborgName + ".");
//You cannot refer to static members using an instance reference.
//MessageBox.Show("A series " + MyRobot.SeriesID + " robot.");
//Use a type name instead.
MessageBox.Show("A series " + Cyborg.SeriesID + " robot."); }
}
public class Cyborg : System.Object
{
private string serialNumber = "A100";
public string cyborgName;
public int cyborgAge = 0;
public static readonly int SeriesID = 100;
}
}