Implementing More Than One Interface

Classes can derive from only one class (and if it doesn’t explicitly derive from a class, it implicitly derives from Object).

Tip

Some languages, such as C++, support inheritance from multiple base classes. C# allows inheritance from only a single class, but interfaces don’t have that limitation.

When you design your class, you can choose not to implement any interfaces, you can implement a single interface, or you can implement more than one. For example, in addition to IStorable, you might have a second interface, ICompressible, for files that can be compressed to save disk space. This new interface might have methods of Compress( ) and Decompress( ), for example. If your Document class can be stored and compressed, you might choose to have Document implement both the IStorable and ICompressible interfaces.

Tip

Both IStorable and ICompressible are interfaces created for this book and are not part of the standard .NET Framework.

Example 13-2 shows the complete listing of the new ICompressible interface and demonstrates how you modify the Document class to implement the two interfaces.

Example 13-2. Implementing multiple interfaces isn’t much more difficult than implementing a single one; you just have to implement the required methods for both interfaces

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Example_13_2_ _ _ _Multiple_Interfaces { interface IStorable { void Read( ); void Write(object obj); int ...

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.