Overriding Interface Methods

When you create an implementing class, you’re 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. In an earlier example, we created a base class Note and a derived class Document. While the Note class implements Read( ) and Write( ) to save to a file, the Document class might implement Read( ) and Write( ) to read from and write to a database.

Example 13-5 uses the Note and Document classes, but we’ve taken out the extra complexity we added in the last few examples, to focus on overriding an interface implementation. Note implements the IStorable-required Read( ) method as a virtual method, and Document overrides that implementation.


Notice that Note does not mark Write( ) as virtual. You’ll see the implications of this decision in the analysis that follows Example 13-5.

The complete listing is shown in Example 13-5.

Example 13-5. You can override an interface implementation in the same way that you would override any virtual method of a parent class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Example_13_5_ _ _ _Overriding_Interface_Implementation { interface IStorable { void Read( ); void Write( ); } public class Note : IStorable { public ...

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

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