#696 – Using a Static Property to Count Instances

A static property is a property that allows access to a data item that is shared across all instances of a class, as opposed to an instance property, where there is a separate copy of the data for each instance.

One common use for a static property is to count the total number of instances of a particular class.  In the example below, the static NumDogs property keeps track of the total number of Dog objects.

    public class Dog
    {
        // Name / Age properties go here

        // Instance constructor
        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
            NumDogs++;
            Console.WriteLine(string.Format("Constructor, # dogs now = {0}", NumDogs));
        }

        // Finalizer
        ~Dog()
        {
            NumDogs--;
            Console.WriteLine(string.Format("Finalizer, # dogs now = {0}", NumDogs));
        }

        // Static properties
        public static int NumDogs { get; protected set; }
    }

If we do the following:

            Dog d = new Dog("Kirby", 15);

            Dog d2 = new Dog("Ruby", 2);
            d = d2;

            GC.Collect();

We get:

Advertisement