Please look at simple code below
public class A{}
public class B: A{}
public class G<T> where T : A
{
public T GetT()
{
return new A();
}
}
This code is incorrect – compiler error “Cannot convert A to return type T”.
But A is actually T. If I change
return new A();
to
return new A() as T;
everything is ok. What is the reason of that behavior?
Thanks in advance
UPD: there was an error in initial question. Now fixed
Reworked answer based on update
Although
Ameets the generic constraintwhere T : A, it’s a concrete type. However, your generic class’sGetT()method has a generic return type ofT, so you have to cast your concrete type to your generic type to make the returns compatible.The old answer holds true for your previous case of returning
new B().Old answer
The generic type constraint says that
Tmust inherit fromA; however, it does not say thatTmust beB(or a derivation of it), althoughBhappens to itself inherit fromAand meet the constraint.So the return type isn’t compatible (
Bis alwaysB, butTis not necessarilyB), and you get the error.