public void Foo<T>(Func<T> bar)
where T: IMyInterface
{
Func<IMyInterface> func = bar;
}
It has been a while since I'd understood covariance, but shouldn't this compile?
Anything bar
can return is also an IMyInterface
. What seems to be the problem?
Covariance and contravariance are terms that refer to the ability to use a more derived type (more specific) or a less derived type (less specific) than originally specified. Generic type parameters support covariance and contravariance to provide greater flexibility in assigning and using generic types.
In . NET Framework 4 and later versions, C# supports covariance and contravariance in generic interfaces and delegates and allows for implicit conversion of generic type parameters.
Covariance permits a method to have a return type that is a subtype of the one defined in the delegate. Contravariance permits a method to have a parameter type that is a base type of the one defined in the delegate type.
A type constraint on a generic type parameter indicates a requirement that a type must fulfill in order to be accepted as a type argument for that type parameter. (For example, it might have to be a given class type or a subtype of that class type, or it might have to implement a given interface.)
Is this a covariance bug in C# 4?
the correct code is:
public void Foo<T>(Func<T> bar)
where T: class, IMyInterface
{
Func<IMyInterface> func = bar;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With