Combining Interfaces

You can also create new interfaces by combining existing interfaces and optionally adding new methods or properties. For example, you might decide to combine the definitions of IStorable and ICompressible into a new interface called IStorableCompressible. This interface would combine the methods of each of the other two interfaces, but would also add a new method, LogOriginalSize( ), to store the original size of the precompressed item:

interface IStorableCompressible : IStorable, ILoggedCompressible
{
    void LogOriginalSize( );
}

Having created this interface, you can now modify Document to implement IStorableCompressible:

public class Document : IStorableCompressible

You now can cast the Document object to any of the four interfaces you’ve created so far:

IStorable storableDoc = doc as IStorable;
ILoggedCompressible logCompressDoc = doc as ILoggedCompressible; 
ICompressible compressDoc = doc as ICompressible;
IStorableCompressible storCompressDoc = doc as IStorableCompressible;

When you cast to the new combined interface, you can invoke any of the methods of any of the interfaces it extends or combines. The following code invokes four methods on iscDoc (the IStorableCompressible object). Only one of these methods is defined in IStorableCompressible, but all four are methods defined by interfaces that IStorableCompressible extends or combines.

if (iscDoc != null) { storCompressDoc.Read( ); // Read( ) from IStorable storCompressDoc.Compress( ); // Compress( ) from ICompressible ...

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.