Inheritance on a constrained generic type parameter

Because you can’t. Generics are not templates. You shouldn’t think about them like C++ templates and expect the same behavior. They are fundamentally different concepts.

The C# specification explicitly prohibits usage of type parameters as base class:

C# 3.0 Language Specification: Type Parameters (§4.5)

A type parameter cannot be used directly to declare a base class (§10.2.4) or interface (§13.1.3).

Update:

I understand what you want to do and its use. This is a traditional use case of C++ templates. Specifically, if this was possible to do using C# generics, things like Moq library could benefit from it. The problem is, C++ templates are compile time “find and replace” constructs while C# generics are a run time thing.

To demonstrate this fact, for this class:

class Test<T> where T : class {
    // whatever contents it might have...
} 

only a single IL will be emitted at compile time and at run time, the JIT compiler would generate a single native code for all reference-type type parameters. This is not like C++ templates at all, where native code would be emitted for every T separately (it’s subject to optimization but conceptually, they are completely separate pieces of code).

Leave a Comment