Overriding Interface Implementations

An implementing class is free to mark any or all of the methods from the interface as virtual. Derived classes can then override or provide new implementations, just as they might with any other virtual instance method.

For example, a Document class might implement the IStorable interface and mark its Read() and Write() methods as virtual. The developer might later derive new types from Document, such as a Note type. While the Document class implements Read() and Write to save to a File, the Note class might implement Read() and Write() to read from and write to a database.

Example 14-6 strips down the complexity of the previous examples and illustrates overriding an interface implementation. In this example, you’ll derive a new class named Note from the Document class.

Document implements the IStorable-required Read() method as a virtual method, and Note overrides that implementation.


Notice that Document does not mark Write() as virtual. You’ll see the implications of this decision in the analysis section that follows Example 14-6.

The complete listing is shown in Example 14-6.

Example 14-6. Overriding an interface implementation

using System;

namespace OverridingInterfaces
    interface IStorable
        void Read();
        void Write();

    // Simplify Document to implement only IStorable
    public class Document : IStorable
        // the document constructor
        public Document(string s) 
                "Creating document with: {0}", s);
 // Make read ...

Get Learning C# now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.