1

According to this for all generic class with reference types only one closed type generated. So when I declare static field in generic class, it should be common for all this types. But when I try to implement this behaviour, I get unexpected result:

class Generic<T>
{
    public static int Number { get; set; }
}

class A { }
class B { }

Generic<A>.Number = 1;
Generic<B>.Number = 2;

Console.Write(Generic<A>.Number); // output is "1"
Console.Write(Generic<B>.Number); // output is "2"

Could anybody explain me this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Alexander
  • 560
  • 3
  • 14
  • 1
  • MSDN says: "Generics work somewhat differently for reference types. The first time a generic type is constructed with any reference type, the runtime creates a specialized generic type with object references substituted for the parameters in the MSIL. Then, every time that a constructed type is instantiated with a reference type as its parameter, regardless of what type it is, the runtime reuses the previously created specialized version of the generic type.". So we should have one type for Generic and Generic. – Alexander Sep 09 '15 at 17:04
  • The article is somewhat misleading if you try to read it as explanation of generics (instead of "deep internals of generics"). Indeed there is one instance of compiled code for all reference types, but data for each type is still unique to comply with C#/.Net expected behavior - i.e. for reflection to work type needs to know exact concrete type. – Alexei Levenkov Sep 09 '15 at 17:09
  • I understand what you mean but there MSDN is talking about **code**. All specialized types will share same generated code (for reference types). Data, however, even static are not shared. See dupe for specs about this. – Adriano Repetti Sep 09 '15 at 17:12
  • This is not a duplicate. The other question does not have answers specifically for reference types. I still don't know why separated static field for generic classes with reference type parameter created. How is it even possible to have different static fields for each reference types if the underlying code is the same? – Ádám Bozzay Sep 06 '19 at 08:11

0 Answers0