#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:

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: