Explicit virtual interfaces

A

amaca

This does what I expect (as it should, it's from Hoffman and Kruger's C#
Unleashed):

public interface ISpeak
{
void Speak();
}

public abstract class Animal : ISpeak
{
public abstract void Speak();
}

public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine( "Woof" );
}
}

public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine( "Meow" );
}
}


that is, it allows me to define an interface, implement it in a base class
as an abstract method, and then override that method in an inherited class.
But I need to implement two interfaces with the same signature, and this
doesn't compile:

public interface ISpeak
{
void Speak();
}

public abstract class Animal : ISpeak
{
abstract void ISpeak.Speak(); // abstract not allowed
}

class Dog : Animal, ISpeak
{
override void ISpeak.Speak() // override not allowed
{
Console.WriteLine( "Woof" );
}
}

public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine( "Meow" );
}
}

Is this simply not allowed (in which case why not?) or is there some arcane
syntax to allow this?

TIA

Andrew
 
J

Jon Skeet [C# MVP]

amaca wrote:

But I need to implement two interfaces with the same signature, and this
doesn't compile:

Do you want to use the same implementation for both interfaces? If so,
I'd create a new abstract method in the base class (eg SpeakImpl) and
implement the two interfaces in a way which calls SpeakImpl.

Jon
 
A

amaca

Do you want to use the same implementation for both interfaces? If so,
I'd create a new abstract method in the base class (eg SpeakImpl) and
implement the two interfaces in a way which calls SpeakImpl.

Actually no, but it does seem the obviously easy way to go, so I'll do that.
Thanks.

Andrew
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You will need to use explicit declaration:

public interface ISpeak{ void A();}

abstract class C1:ISpeak
{
public abstract void A();

void ISpeak.A()
{
}

}
class C2:C1, ISpeak
{
public override void A()
{

}

void ISpeak.A()
{
}

}
 

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