return Inherited class instead of "original" class

  • Thread starter Thread starter Karsten Schramm
  • Start date Start date
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
 
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
 
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
 
Back
Top