As opposed to C++ templates, .NET generics are evaluated in runtime, not at compile-time. Semantically, if you instantiate the generic class with different type parameters, those will behave as if it were two different classes, but under the hood, there is only one class in the compiled IL (intermediate language) code.
Generic types
The difference between different instantiatons of the same generic type becomes apparent when you use Reflection: typeof(YourClass<int>)
will not be the same as typeof(YourClass<string>)
. These are called constructed generic types. There also exists a typeof(YourClass<>)
which represents the generic type definition. Here are some further tips on dealing with generics via Reflection.
When you instantiate a constructed generic class, the runtime generates a specialized class on the fly. There are subtle differences between how it works with value and reference types.
- The compiler will only generate a single generic type into the assembly.
- The runtime creates a separate version of your generic class for each value type you use it with.
- The runtime allocates a separate set of static fields for each type parameter of the generic class.
- Because reference types have the same size, the runtime can reuse the specialized version it generated the first time you used it with a reference type.
Generic methods
For generic methods, the principles are the same.
- The compiler only generates one generic method, which is the generic method definition.
- In runtime, each different specialization of the method is treated as a different method of the same class.