tags:

views:

445

answers:

5

Is there any rational reason why the code below is not legal in C#?

class X: IA, IB
{
    public X test() // Compliation Error, saying that X is not IB
    {
        return this;
    }
}

interface IA 
{
    IB test();
}
interface IB { };
+4  A: 

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.

Thorarin
+3  A: 

Because C# does not support co and contravriance for interfaces in compile time. This way an implementation of IA.Test() method must exactly match its declaration. You can, however, return instance of X in runtime

Przemaas
+1  A: 

public X test();

You must declare a body for all methods in any class that's not abstract.

Try this:

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

interface IA
{
    IB test();
}
interface IB { };
skalburgi
+6  A: 

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
{
}
Brian Gideon
+1 for providing the work around. Thanks!
Piotr Czapla
+11  A: 

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.

Eric Lippert
fair enough :), thank you for the answer.
Piotr Czapla
Do you know if any additional information about #2 is available? I enjoy reading about language issues like that. :)
280Z28