Inheritance??

A

andreister

public interface IFood { }

public interface IMonkey { void Eat(IFood food); }

public class Bread : IFood { }

public class Gorilla : IMonkey
{
public void Eat(Bread bread)
{ }
}

Compiler error: 'Gorilla' does not implement interface member
'IMonkey.Eat(IFood)'
I would expect there should be no problem with it because Bread is
inherited from IFood... Could anybody explain?

Thanks, Andrew
 
N

Nicholas Paldino [.NET/C# MVP]

Andrew,

No, this is not the case. From the C# language specification, section
20.4.2, titled "Interface mapping":

For purposes of interface mapping, a class member A matches an interface
member B when:
a.. A and B are methods, and the name, type, and formal parameter lists of
A and B are identical.
In this case, the parameter lists are not identical.

What you are looking for is referred to as covariance, and it is
something that C# doesn't support in implicit interface implementations.
 
J

Jon Skeet [C# MVP]

public interface IFood { }

public interface IMonkey { void Eat(IFood food); }

public class Bread : IFood { }

public class Gorilla : IMonkey
{
public void Eat(Bread bread)
{ }
}

Compiler error: 'Gorilla' does not implement interface member
'IMonkey.Eat(IFood)'
I would expect there should be no problem with it because Bread is
inherited from IFood... Could anybody explain?

Suppose we had Peanut which was also derived from IFood. Given the
interface, we'd expect to be able to do:

IMonkey gorilla = new Gorilla();
gorilla.Eat (new Peanut());

But you haven't specified what can be done with peanuts - only bread.
That means you're not fulfilling the interface's contract.

Now, if you'd written:

public void Eat(object o)

then it *still* wouldn't compile, because C# doesn't support parameter
contravariance for interfaces - but then at least that would be a
shortcoming in C# :)

Basically, for interfaces you have to implement *exactly* the methods
specified.
 

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