C# Static variables of FooBar<T> are per T

|
I discovered a comment about a thir of the way down Eric Lippert's recent blog entry, where he asked people to share their experiences of discovering something non-intuitive about programming languags:

Discovering that the static variables of generic type Foo<t> were per T was interesting (and I see why they are that way) just that it was quite subtle when I first hit it.
What would you know, it's true:

    class Program
    {
        static void Main(string[] args)
        {
            int intGenericClassId = GenericClass<int>.GetId();
            int boolGenericClassId = GenericClass<bool>.GetId();

            print(typeof(GenericClass<int>).Name, intGenericClassId);
            print(typeof(GenericClass<bool>).Name, boolGenericClassId);

            GenericClass<int>.SetId(3);
            Console.WriteLine("Set <GenericClass<int> to Id of 3");

            intGenericClassId = GenericClass<int>.GetId();
            boolGenericClassId = GenericClass<bool>.GetId();

            print(typeof(GenericClass<int>).Name, intGenericClassId);
            print(typeof(GenericClass<bool>).Name, boolGenericClassId);

            Console.ReadKey();
        }

        private static void print(string typeName, int value)
        {
            Console.WriteLine("Starting value of Int for {0}: {1}", typeName, value);
        }

        internal static class GenericClass<T> where T : struct
        {
            private static int _id = 0;
            static GenericClass()
            {
            }
            public static int GetId()
            {
                return _id;
            }
            public static void SetId(int value)
            {
                _id = value;
            }
        }
    }

About this Entry

This page contains a single entry by Robert Wray published on January 28, 2009 8:30 AM.

More delusional ramblings was the previous entry in this blog.

CruiseControl as a Monitoring tool is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.04