Overriding Interface Implementations

An implementing class is free to mark any or all of the methods that implement the interface as virtual. Derived classes can override or provide new implementations. For example, a Document class might implement the IStorable interface and mark the Read( ) and Write( ) methods as virtual. The Document might Read( ) and Write( ) its contents to a File type. The developer might later derive new types from Document, such as a Note or EmailMessage type, and he might decide that Note will read and write to a database rather than to a file.

Example 8-4 strips down the complexity of Example 8-3 and illustrates overriding an interface implementation. The Read( ) method is marked as virtual and implemented by Document. Read( ) is then overridden in a Note type that derives from Document.

Example 8-4. Overriding an interface implementation

using System;

interface IStorable
{
   void Read( );
   void Write( );
}

// Simplify Document to implement only IStorable
public class Document : IStorable
{
   // the document constructor
   public Document(string s) 
   {
      Console.WriteLine(
         "Creating document with: {0}", s);
        
   }
    
   // Make read virtual
   public virtual void Read( ) { Console.WriteLine( "Document Read Method for IStorable"); } // NB: Not virtual! public void Write( ) { Console.WriteLine( "Document Write Method for IStorable"); } } // Derive from Document public class Note : Document { public Note(string s): base(s) { Console.WriteLine( "Creating note with: {0}", s); } ...

Get Programming C#, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.