Possible Duplicate:
Does C# support return type covariance?
I'm not sure if I'm just being stupid...
If I have an interface:
public interface IMoop
{
object Moop();
}
Why can't I implement it like so (I guess this would use implicit Covariance?)
public class MoopImplementor : IMoop
{
string Moop();
}
Any instance of MoopImplementor would meet the contract specified by IMoop, so it seems like this should be ok.
Please enlighten me :)
EDIT: To be clear- since the implementing class returns something that inherits from the return type of the Interfaced method - I feel this should work. Specifically, a string
IS an object
. (and the same goes for any other inhertiance chain).
C# does not support return type covariance for the purposes of interface implementation or virtual method overrding. See this question for details:
Does C# support return type covariance?
C# does support generic covariance and contravariance of interfaces and delegate types that are constructed wtih reference types for the type arguments as of C# 4.
And C# does support return type covariance when converting a method that returns a reference type to a delegate type whose return type is a compatible reference type. (And similarly it supports parameter type contravariance.)
If this subject interests you, I have written a great many articles discussing various versions of variance that C# does and does not support. See
https://blogs.msdn.microsoft.com/ericlippert/tag/covariance-and-contravariance/
for details.
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