Creating Static Fields

A static field is a class field, which means that its data is stored in one location in memory, no matter how many objects are created from its class. In fact, you can use a static field to keep track of how many objects have been created from a particular class. To do that, you might declare a static field, which we'll name numberOfObjects in the example, and increment that field each time the class's constructor is called (an explicit initializer is required for static fields, so we've assigned numberOfObjects the value 0 here):

public class CountedClass
{
  public static int numberOfObjects = 0;

  public CountedClass()
  {
    numberOfObjects++;
  }
}

Now each time a new object of this class is created, numberOfObjects is incremented. ...

Get Microsoft® Visual C#® .NET 2003 Kick Start now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.