Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I implement an Interface this way? [duplicate]

Tags:

c#

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).

like image 917
Dave Bish Avatar asked Apr 26 '12 17:04

Dave Bish


1 Answers

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.

like image 67
Eric Lippert Avatar answered Sep 24 '22 07:09

Eric Lippert