Are the placeholders of Generics compiled as an actual data type?

79 views Asked by At

My question relates to how exactly Generics (in C#) are compiled.

Code sample

public class MyClass<Foo>
{
    public void MyMethod(Foo test)
    {

    }
}

Questions

  1. Would the Foo type in MyMethod be compiled as a concrete type? I would imagine not as this would require multiple versions of the same class being created (should it be instantiated with different types), so I imagine a generic type is properly supported rather than just being syntax sugar?
  2. On a low level, how are generics implemented? Are the generic values against a class/method stored as special hidden fields?

I think my assumptions are incorrect, but I'm trying to get a feel for the inner workings behind the scenes.

Update

If I understand this article correctly, a new class in the IL is created during runtime with the concrete types.

As a result, the runtime generates another version of the generic type and substitutes a long in the appropriate locations in MSIL. Conversions are no longer necessary because each specialized generic class natively contains the value type.

https://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx

0

There are 0 answers