#342 – Using a Static Variable to Count Instances of a Class

Recall that static variables in a class are not specific to a particular class, but that there is a single copy of each static variable regardless of the number of instances of the class that exist.

It’s fairly common to use a static variable to keep track of how many instances of a class have been created.

        // Total # of instances that have been created
        public static int NumDogs { get; protected set; }

        // Static constructor initializes NumDogs
        static Dog()
        {
            NumDogs = 0;
        }

        // Instance properties
        public string Name { get; set; }
        public int DogNumber { get; set; }   // unique dog-number, 1..n

        public Dog(string name)
        {
            Name = name;

            // Increment dog count and assign dog number
            NumDogs++;
            DogNumber = NumDogs;
        }