C++ templates are generated at compile time. I heard that C# generics are generated at runtime. This mean that it is generated at the moment of IL -> execution? Is this part also included in the runtime?
1 Answers
Your assertions are correct, C++ templates are completely constructed at compilation, .Net creates the types it needs at run-time. Although, generic typing needs to be resolved at compile time, the generated classes for the MSIL that get used and reused are generated at run-time (albeit slightly differently for Value Types and Reference Types)
Differences Between C++ Templates and C# Generics (C# Programming Guide)
C# Generics and C++ templates are both language features that provide support for parameterized types. However, there are many differences between the two. At the syntax level, C# generics are a simpler approach to parameterized types without the complexity of C++ templates. In addition, C# does not attempt to provide all of the functionality that C++ templates provide. At the implementation level, the primary difference is that C# generic type substitutions are performed at runtime and generic type information is thereby preserved for instantiated objects.
Generics in the Run Time (C# Programming Guide)
Value Types
When a generic type is first constructed with a value type as a parameter, the runtime creates a specialized generic type with the supplied parameter or parameters substituted in the appropriate locations in the MSIL. Specialized generic types are created one time for each unique value type that is used as a parameter.
Reference Types
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. This is possible because all references are the same size.

- 79,002
- 9
- 103
- 141