Interface casting

image_pdfimage_print

   

/*
Learning C# 
by Jesse Liberty

Publisher: O'Reilly 
ISBN: 0596003765
*/
 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
     class Document : IStorable
     {
         // the document constructor
         public Document(string s)
         {
             Console.WriteLine("Creating document with: {0}", s);

         }

         // implement IStorable
         public void Read()
         {
             Console.WriteLine(
                 "Implementing the Read Method for IStorable");
         }

         public void Write(object o)
         {
             Console.WriteLine(
                 "Implementing the Write Method for IStorable");
         }

         public int Status
         {
             get { return status; }
             set { status = value; }
         }

         // hold the data for IStorable's Status property
         private int status = 0;
     }


    public class TesterInterfaceDemoCasting
    {

       [STAThread]
       static void Main()
       {
           Document doc = new Document("Test Document");

           // only cast if it is safe
           if (doc is IStorable)
           {
               IStorable isDoc = (IStorable) doc;
               isDoc.Read();
           }
           else
           {
               Console.WriteLine("Could not cast to IStorable");
           }

           // this test will fail
           if (doc is ICompressible)
           {
               ICompressible icDoc = (ICompressible) doc;
               icDoc.Compress();
           }
           else
           {
               Console.WriteLine("Could not cast to ICompressible");
           }       }
    }
 }