Why cannot C# generics derive from one of the generic type parameters like they can in C++ templates? [duplicate]

Well, start by asking yourself what could possibly go wrong with class C<T> : T { }. A huge number of things come immediately to mind:

What if T is a struct? What if T is a sealed class type? What if T is an interface type? What if T is C<T>?! What if T is a class derived from C<T>? What if T is an abstract type with an abstract method? What if T has less accessibility than C ? What if T is System.ValueType? (Can you have a non-struct which inherits from System.ValueType?) What about System.Delegate, System.Enum, and so on?

Those are the easy, obvious ones. The proposed feature opens up literally hundreds, if not thousands of more subtle questions about the interaction between the type and its base type, all of which would have to be carefully specified, implemented and tested. We’d undoubtedly miss some, and thereby cause breaking changes in the future, or saddle the runtime with implementation-defined behaviour.

The costs would be enormous, so the benefit had better be enormous. I’m not seeing an enormous benefit here.

Leave a Comment