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.

Tip

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 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.