Consider the following generic method:
public T2 Frob<T1, T2>(T1 item)
where T1 : class, T2
=> item as T2;
The compiler will refuse to compile this code; The type parameter 'T2' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint
Ok, this is easily solvable simply doing:
public T2 Frob<T1, T2>(T1 item)
where T1 : class, T2
where T2 : class
=> item as T2;
But isn't this redundant? Is there any possible T2
that is not a class
considering the constraints already in place for T1
?
My question is not why this "inference" wasn't implemented in the compiler, the reason could simply be "no one thought about it" and thats OK. I'm more interested in knowing if my reasoning is correct in that T2
is effectively and in all cases constrained to class
in the first example even if its not explicitly enforced.
T1
do also apply forT2
? They have nothing in common, in particular whilstT1
derives fromT2
,T2
doesn´t know anything ofT1
. – MusjidT2
itself isn´t constrained to anything, it could be even astruct
. – MusjidT1
. – BoninT2
cannot be a value type becauseT1
cannot be derived from a value type. So it necessarily has to be a reference type. – Vicissitude