Inheriting from Multiple Interfaces with the Same Method Names

Tags: Interfaces, Interview Questions

I was asked this interesting question at a job interview this week. Can you inherit from multiple interfaces if those interfaces have the same signatures? Here's an example:

public interface IGuitar
{
	string PlaySolo(string notes);
}

public interface IAxe
{
	string PlaySolo(string notes);
}

Well one thing you can do is implement each method explicitly. Explicit implementation looks like this.

Explicit Implementation

public class Strat : IGuitar, IAxe
{
	string IGuitar.PlaySolo(string notes)
	{
		return notes.ToUpper() + "  Guitar!!";
	}

	string IAxe.PlaySolo(string notes)
	{
		return notes.ToUpper() + "  Axe!!";
	}
}

The pesky thing with explicit implementation is that you have to cast your object to the interface type in order to call the explicitly implemented method, like so.

Strat strat = new Strat();
Console.WriteLine(((IGuitar)strat).PlaySolo("Playing my solo"));
Console.WriteLine(((IAxe)strat).PlaySolo("Playing my solo"));

This will print:
   PLAYING MY SOLO Guitar!!
   PLAYING MY SOLO Axe!!

This has a boxing performance penalty the has to be considered.

If you want each similarly named method of each interface to have different functionality, you have to use explicit implementation. But what if you don’t; then you can use implicit implementation and implement the similarly named method only once like so:

Implicit Implementation

public class LesPaul : IGuitar, IAxe
{
	public string PlaySolo(string notes)
	{
		return notes.ToUpper() + "!!";
	}
}

This class implements two interfaces with one method, sort of like killing two birds with one stone. (No birds were actually harmed while implementing these interfaces)

No Comments

Add a Comment