Implementing More Than One Interface

Classes can derive from only one class (and if you don’t explicitly derive from a class, then you implicitly derive from Object). Classes can implement any number of interfaces. When you design your class, you can choose not to implement any interfaces, you can implement a single interface, or you can implement two or more interfaces. For example, in addition to IStorable, you might have a second interface, ICompressible, for files that can be compressed to save disk space. 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 14-2 shows the complete listing of the new ICompressible interface and demonstrates how you modify the Document class to implement the two interfaces.

Example 14-2. IStorable and ICompressible, implemented by Document

using System;

namespace InterfaceDemo
{
    interface IStorable
    {
        void Read();
        void Write(object obj);
        int Status { get; set; }

    }

    // here's the new interface
    interface ICompressible
                   {
                       void Compress();
                       void Decompress();
                   }

 
    // Document implements both interfaces
    public class Document : IStorable, ICompressible { // the document constructor public Document(string s) { Console.WriteLine("Creating document with: {0}", s); } // implement IStorable public void Read() { Console.WriteLine( "Implementing ...

Get Learning C# 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.