-4

Possible Duplicate:
C#: Interfaces - Implicit and Explicit implementation

I was reading about Interface reimplementation. I am not sure what does this mean? " implicitly implementing a member and explicitly implementing a member"

Sample code:

Explicit member implementation:

public interface IUndoable { void Undo(); }
public class TextBox : IUndoable
{
void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); }
}
public class RichTextBox : TextBox, IUndoable
{
public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); }
}

Implicit member implementation:

public class TextBox : IUndoable
{
public void Undo() { Console.WriteLine ("TextBox.Undo"); }
}
Community
  • 1
  • 1
Charu
  • 2,679
  • 6
  • 35
  • 52

1 Answers1

7

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.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459