C# – How are generics implemented

cgenerics

This is the question from compiler internals perspective.

I am interested in generics, not templates (C++), so I marked the question with C#. Not Java, because AFAIK the generics in both languages differ in implementations.

When I look at languages w/o generics it is pretty straightforward, you can validate the class definition, add it to hierarchy and that's it.

But what to do with generic class, and more importantly how handle references to it? How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Let's say I see a call:

var x = new Foo<Bar>();

Do I add new Foo_Bar class to hierarchy?


Update: So far I found only 2 relevant posts, however even they don't go into much details in sense "how to do it by yourself":

Best Answer

How to make sure that static fields are singular per instantiations (i.e. each time generic parameters are resolved).

Each generic instantiation has its own copy of the (confusingly named) MethodTable, which is where static fields are stored.

Let's say I see a call:

var x = new Foo<Bar>();

Do I add new Foo_Bar class to hierarchy?

I'm not sure it's useful to think of the class hierarchy as some structure that actually exists at runtime, it's more of a logical construct.

But if you consider MethodTables, each with an indirect pointer to its base class, to form this hierarchy, then yeah, this adds new class to the hierarchy.