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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: