Reimplementing an Interface in a Subclass - CSharp Custom Type

CSharp examples for Custom Type:interface

Introduction

A subclass can reimplement any interface member already implemented by a base class.

public interface IUndoable { void Undo(); }                                                    
public class TextBox : IUndoable                                                               
{                                                                                              
  void IUndoable.Undo() => Console.WriteLine ("TextBox.Undo");
}

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

Calling the reimplemented member through the interface calls the subclass's implementation:

RichTextBox r = new RichTextBox();
r.Undo();                 // RichTextBox.Undo      Case 1
((IUndoable)r).Undo();    // RichTextBox.Undo      Case 2

Assuming the same RichTextBox definition, suppose that TextBox implemented Undo implicitly:

public class TextBox : IUndoable
{
  public void Undo() => Console.WriteLine ("TextBox.Undo");
}

This would give us another way to call Undo, which would "break" the system, as shown in Case 3:

RichTextBox r = new RichTextBox();
r.Undo();                 // RichTextBox.Undo      Case 1
((IUndoable)r).Undo();    // RichTextBox.Undo      Case 2
((TextBox)r).Undo();      // TextBox.Undo          Case 3

Case 3 demonstrates that reimplementation hijacking is effective only when a member is called through the interface and not through the base class.


Related Tutorials