O'Reilly logo

Learning C# 3.0 by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required