Why C# doesn't allow inheritance of return type when implementing an Interface

UPDATE: This answer was written in 2009. After two decades of people proposing return type covariance for C#, it looks like it will finally be implemented; I am rather surprised. See the bottom of https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/ for the announcement; I'm sure details will follow.


This feature is called "return type covariance". C# does not support it for the following reasons:

1) The CLR doesn't support it. To make it work in C#, we'd have to just spit a whole bunch of little helper methods that do casts on the return type to the right thing. There's nothing stopping you from doing that yourself.

2) Anders believes that return type covariance is not a good language feature.

3) \We have lots of higher priorities for the language. We have only limited budgets and so we try to only do the best features we can in any given release. Sure, this would be nice, but it's easy enough to do on your own if you want to. Better that we spend the time adding features that improve the developer experience or add more representational power to the language.


You could use explicit interface implementation to avoid the problem.

class  X : IA, IB
{
  public X test()
  {
    return this;
  }

  IB IA.test()
  {
    return this;
  }
}

interface IA
{
  IB test();
}

interface IB
{
}

The signatures must match exactly to what the interface specifies. There's no reason you cannot return an instance of X from the method, but the method signature will have to use IB.

As for a rational reason.. it's probably preferable from a code readability point of view.

You could implement the interface explicitly, and provide an alternative signature that returns X that is not defined by the interface. If you know your IA is actually an X, you could use that instead.

Tags:

C#

.Net