#45 – Static Members of a Class

When you create a new object and use a reference variable to call methods of a class, you’re using instance members of that class.  Instance members interact with just that instance of the class.

You can also work with class members without creating an instance of the class.  Static class members operate on the class itself, rather than on instances of the class.

To invoke static members, you use the name of the class, rather than a variable that points to an instance of the class.

In the example below, we create two Person objects and then work with both instance and static methods.

 // Create 2 new Person objects
 Person p1 = new Person("Sean", 46);
 Person p2 = new Person("Fred", 28);
 string info = p1.DoReport();       // Acts on p1
 int age = p2.Age;                  // p2's Age

 int numFolks = Person.PersonCount;   // Static property
 Person.DoGeneralPersonStuff();       // Static method
Advertisements