O'Reilly logo

Learning C# 2005, 2nd Edition 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 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. 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 strips down the complexity of the previous examples and illustrates 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. Overriding an interface implementation

using System; namespace OverridingAnInterfaceImplementation { interface IStorable { void Read( ); void Write( ); } public class Note : IStorable { public Note( string s ) { Console.WriteLine( "Creating Note with: {0}", s ); } // NB: virtual public virtual void Read( ) { Console.WriteLine( "Note Read Method for IStorable" ); } // NB: Not virtual! public void Write( ) { Console.WriteLine( "Note ...

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