DekGenius.com
Team LiB   Previous Section   Next Section

14.5 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 pre-compressed 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 isDoc = doc as IStorable;
ILoggedCompressible ilDoc = doc as ILoggedCompressible;
ICompressible icDoc = doc as ICompressible;
IStorableCompressible iscDoc = 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)
{
    iscDoc.Read();               // Read() from IStorable
    iscDoc.Compress();           // Compress() from ICompressible
    iscDoc.LogSavedBytes();      // LogSavedBytes() from          
                                 // ILoggedCompressible    
    iscDoc.LogOriginalSize();    // LogOriginalSize() from 
                                 // IStorableCompressible 
}
    Team LiB   Previous Section   Next Section