0

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

Brummy
  • 183
  • 1
  • 11
  • I don't think that question satisfies my questions above. Maybe it does to some people, but I think that question assumes more knowledge than I currently do of how the IL code might work. – Brummy Jan 06 '17 at 16:56
  • 1
    If you're interested in the answer to questions like, *"On a low level, how are generics implemented?"*, it might be time to increase your familiarity with IL. :-) – Cody Gray - on strike Jan 06 '17 at 19:11
  • Definitely. I sometimes view IL code to get a rough idea of what's going on, but I've never studied it. I think the answer I'm looking for here however is more related to runtime? I would think. – Brummy Jan 06 '17 at 20:54
  • 1
    No, generics aren't handled at runtime. The answer to the linked duplicate contains a quote that specifically addresses that: *"We do the overload resolution once and bake in the result. [...] The IL we’ve generated for the generic type already has the method its going to call picked out."* – Cody Gray - on strike Jan 07 '17 at 12:36

0 Answers0