#1,044 – How Static Data Behaves in Generic Types

There is only a single copy of each static data item, rather than one copy for each instance of the class.

When you have a static data item in a generic class, there is a single copy of that data item for each constructed type based on the generic type.  A constructed type is a type declaration that is based on a generic type, providing arguments for the generic type’s type parameters.

Assume that we define a PileOf<T> type that has a static NumInAllPiles field, incremented as part of an Add method.  We reference the static field using the constructed class name and see that each constructed type has its own copy of the static data.

            // Pile of 1 dog
            PileOf<Dog> pile1 = new PileOf<Dog>();
            pile1.Add(new Dog("Bowser"));

            // Pile of 2 dogs
            PileOf<Dog> pile2 = new PileOf<Dog>();
            pile2.Add(new Dog("Kirby"));
            pile2.Add(new Dog("Fido"));

            // Pile of 1 cat
            PileOf<Cat> pile3 = new PileOf<Cat>();
            pile3.Add(new Cat("Fluffy"));

            Console.WriteLine(PileOf<Dog>.NumInAllPiles);  // 3
            Console.WriteLine(PileOf<Cat>.NumInAllPiles);  // 1
Advertisements