#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
            DogNumber = NumDogs;

#30 – Types, Variables, Values, Instances

In C#, a type dictates what kind of values can be stored in a variable.  A variable is a storage location for some data.  Every variable is an instance of a specific type and will have a value that can change during the lifetime of a program.

Constants are variables whose values do not change.  They also have a specific type.

Expressions resolve to a particular value when they are evaluated.  They also have a specific type.

There are a number of built-in types in C#  (e.g. int, float) as well as constructs that allow you to create your own types (e.g. class, enum).