Why, when inheriting from generics, all restrictions are not inherited, and as a result, we have to drag the constraint of inheritance.

Is there some kind of sacred meaning that Microsoft didn’t give this opportunity to? It seems that without duplicating the restrictions, the compiler will swear => there is no possibility to put alternative restrictions on the levels above.

class Generic1<T> where T : class { } class Generic2<T> : Generic1<T> where T : class { } 

1 answer 1

The sacred meaning is that C # is a language with a direct order of type inference, and not the reverse.

For example, in the expression double x = 1 / 2 , the operator / means integer division, not real - because the operators are integer. The language is not able to deduce the type of operands based on the intended type of result.

Also for types. Restrictions on type parameters are their types. Base class - calculated expression. The type of the calculated expression is determined based on the types of the operands, and vice versa is impossible.


You just got used to the simplest forms of inheritance - Foo<T> : Bar<T> . But you can write like this: Foo<A, B> : Bar<Baz<A, B>.C> . What restrictions should be inherited from in such cases? In theory, we must inherit the limitations of the class Baz. But it will be a reverse type inference.

  • 2
    "The language does not know how to deduce the type of operands based on the intended type of result" - it seems that the lambas disagree with you ... - Qwertiy
  • @Qwertiy: Rather, it doesn’t know how to output, but doesn’t output. Not because stupid, but because he decided so. - VladD