return Inherited class instead of "original" class

K

Karsten Schramm

Hi,

why doesn't this compile:


class Program
{
public static void Main()
{
ClassA classA = new ClassA();

classA.DoSomethingOnA().DoSomethingOnB();
}
}

class ClassA : InterfaceA
{
public ClassB DoSomethingOnA() // <-- Error
{
Console.WriteLine("DoSomethingOnA");
return (new ClassB());
}
}

class ClassB : InterfaceB
{
public void DoSomethingOnB()
{
Console.WriteLine("DoSomethingOnB");
}
}

interface InterfaceA
{
InterfaceB DoSomethingOnA();
}

interface InterfaceB
{
void DoSomethingOnB();
}


ClassB is always InterfaceB, so in my opinion it should compile.

Thx
 
J

Jon Skeet [C# MVP]

Karsten said:
why doesn't this compile:

<snip>

Because C# (and .NET in general? not sure) doesn't support covariance
of return types for interfaces. I agree it's a bit of a pain.

Jon
 
B

Barry Kelly

Jon Skeet said:
<snip>

Because C# (and .NET in general? not sure) doesn't support covariance
of return types for interfaces. I agree it's a bit of a pain.

Yes, the CLR doesn't support covariance on the return type of the method
when implementing an interface. One way around it is to explicitly
implement the interface, and have the covariant version public. That
way, you can delegate to the public version in the explicit
implementation.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top