2

Following test code outputs 1 for val3 not 3. Why?

    private void test()
    {
        MyClass<string> c1 = new MyClass<string>();
        int val1 = c1.IncrementGlobalValue();//--> 1

        MyClass<string> c2 = new MyClass<string>();
        int val2 = c2.IncrementGlobalValue();//--> 2


        MyClass<int> c3 = new MyClass<int>();
        int val3 = c3.IncrementGlobalValue();//--> 1

        MyClass<int> c4 = new MyClass<int>();
        int val4 = c4.IncrementGlobalValue();//--> 2
    }

    internal class MyClass<T>
    {
        private static int globalValue = 0;
        internal int IncrementGlobalValue()
        {
            return ++globalValue;
        }
    }
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Koray
  • 1,768
  • 1
  • 27
  • 37

2 Answers2

9

Generics create new types which have separate static state.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
3

Pretend generics didn't exist, and < and > where just characters you could use as part of a class name. In that case, MyClass<string> and MyClass<int> would be two completely different names.

That's kind of what's going on here. The generic MyClass<T> provides a template for the types, but each separate specialized use is still its own unique type with its own unique static state.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794