Creating Static Properties

Like fields, properties can also be static, which means you don't need an object to use them. As an example, we'll convert the static field numberOfObjects in the static fields example (see Listing 3.7) into a property of the same name. That's easy enough—all we have to do is to implement the new property like this (note that the value of the property is stored in a private field, which must be static so we can access it from the static property):

public class CountedClass
{
  private static int number = 0;

  public CountedClass()
  {
    number++;
  }

  public static int NumberOfObjects
					  {
					   get
					   {
					     return number;
					   }
					   set
					   {
					     number = value;
					   }
					  }
}

Now we can use this new static property as we used the static field earlier, ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.