Explicit interface implementation allows you to implement different interfaces which have members with same signature. Also it allows you to hide interface implementation (implemented members will be available only via reference of interface type):
public interface IUndoable
{
void Undo();
}
public interface IVeryUndoable
{
void Undo();
}
public class TextBox : IUndoable, IVeryUndoable
{
void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); }
void IVeryUndoable.Undo() { Console.WriteLine ("TextBox.VeryUndo"); }
}
In this case you have two methods Undo()
with same signature. But when you hit .
on your textbox variable, none of methods will be available. You need to cast textbox variable to explicitly implemented interface type:
IUndoable undoable = (IUndoable)textbox;
undoable.Undo(); // now member available
Why would you hide some interface implementation? To keep your object API more clean. Example from .net: List<T>
implements implicitly IList<T>
, but hides implementation of non-generic IList
. So, you can pass lists where non-generic IList
expected, but non-generic methods like Add(object value)
do not pollute nice generic interface.
Same with IDisposable
- you can have nice method with name Close
and explicitly implemented Dispose
(which will call your Close
method). API will be clean - only Close
will be visible. But your object will be possible to use in using
blocks.