Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't an interface implementation return a more specific type?

If an interface specifies a property or method to return another interface, why is it not allowed for implementations of the first interface to "change" the return type into a more specific type?

Let's take an example to illustrate:

interface IFoo {     IBar GetBar(); } interface IBar { }  class Foo : IFoo {     // This is illegal, we are not implementing IFoo properly     public Bar GetBar()     {         return new Bar();     } }  class Bar : IBar { } 

I know how to make it work, that's not my concern.

I can just either:

  • Change return type of GetFoo() to IBar, or
  • Explicitly implement the interface and just call GetBar from the IFoo.GetBar() method

What I am really asking is the reasoning for not just allowing the code above to compile. Is there any case where the above doesn't fulfill the contract specified by IFoo.

like image 566
Isak Savo Avatar asked May 29 '12 09:05

Isak Savo


People also ask

Can an interface be a return type?

Answers. By definition of what an interface is it is impossible to return an interface because interfaces cannot be allocated; there cannot be anything to return.

Can interface implementation have extra methods?

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface can contain any number of methods.

Can interface methods have return type in Java?

Generic Interfaces This interface represents an interface which contains a single method called produce() which can produce a single object. Since the return value of produce() is Object , it can return any Java object.

Can Interfaces be used as return types and parameters?

No, it's not possible. The interface serves as a "binding contact" of the signatures that are available. If you want you can have the function return an Object and by that allow different implementations to return values of different types, but: It must be references, not primitives.


1 Answers

Usually, I'd say that it would be a case of balancing the benefit against the added complexity of supporting such a feature. (All features take effort to design, document, implement, test, and then developers need to be educated about them too.) Note that there could be some significant complexities if you wanted to support returning a value type which implemented an interface, for example (as that ends up in a different representation, rather than just a reference).

In this case, I don't believe the CLR even supports such a feature, which would make it very hard for C# to do so cleanly.

I agree it would be a useful feature, but I suspect it hasn't been deemed useful enough to warrant the extra work required.

like image 151
Jon Skeet Avatar answered Oct 05 '22 22:10

Jon Skeet