#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;
        }

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

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

  1. nobody says:

    Increment is not atomic

    not thread safe…

    use : System.Threading.Interlocked.Increment(ref count);

Leave a comment