Interfaces:The As Operator

image_pdfimage_print

   


/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/
// 10 - InterfacesThe As Operator
// copyright 2000 Eric Gunnerson
using System;

public class TheAsOperator
{
    public static void Main()
    {
        DiagramObject[] dArray = new DiagramObject[100];
        
        dArray[0] = new DiagramObject();
        dArray[1] = new TextObject("Text Dude");
        dArray[2] = new TextObject("Text Backup");
        
        // array gets initialized here, with classes that
        // derive from DiagramObject. Some of them implement
        // IScalable.
        
        foreach (DiagramObject d in dArray)
        {
            IScalable scalable = d as IScalable;
            if (scalable != null)
            {
                scalable.ScaleX(0.1F);
                scalable.ScaleY(10.0F);
            }
        }
    }
}

interface IScalable
{
    void ScaleX(float factor);
    void ScaleY(float factor);
}
public class DiagramObject
{
    public DiagramObject() {}
}
public class TextObject: DiagramObject, IScalable
{
    public TextObject(string text)
    {
        this.text = text;
    }
    // implementing IScalable.ScaleX()
    public void ScaleX(float factor)
    {
        Console.WriteLine("ScaleX: {0} {1}", text, factor);
        // scale the object here.
    }
    
    // implementing IScalable.ScaleY()
    public void ScaleY(float factor)
    {
        Console.WriteLine("ScaleY: {0} {1}", text, factor);
        // scale the object here.
    }
    
    private string text;
}


           
          


Operators and Expressions:Type operators:Is

image_pdfimage_print
   


/*
A Programmer's Introduction to C# (Second Edition)
by Eric Gunnerson

Publisher: Apress  L.P.
ISBN: 1-893115-62-3
*/

// 14 - Operators and ExpressionsType operatorsIs
// copyright 2000 Eric Gunnerson
using System;
interface IAnnoy
{
    void PokeSister(string name);
}
class Brother: IAnnoy
{
    public void PokeSister(string name)
    {
        Console.WriteLine("Poking {0}", name);
    }
}
class BabyBrother
{
}

public class TypeoperatorsIs
{
    public static void AnnoyHer(string sister, params object[] annoyers)
    {
        foreach (object o in annoyers)
        {
            if (o is IAnnoy)
            {
                IAnnoy annoyer = (IAnnoy) o;
                annoyer.PokeSister(sister);
            }
        }
    }
    public static void Main()
    {
        TestoperatorsIs.AnnoyHer("Jane", new Brother(), new BabyBrother());
    }
}
           
          


Demonstrate as

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/


// Demonstrate as. 
 
using System; 
 
class A {} 
class B : A {} 
 
public class CheckCast1 { 
  public static void Main() { 
    A a = new A(); 
    B b = new B(); 
 
    b = a as B; // cast, if possible 
 
    if(b==null)  
      Console.WriteLine("Cast b = (B) a is NOT allowed."); 
    else 
      Console.WriteLine("Cast b = (B) a is allowed"); 
  } 
}


           
          


Use is to avoid an invalid cast

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/


// Use is to avoid an invalid cast. 
 
using System; 
 
class A {} 
class B : A {} 
 
public class CheckCast { 
  public static void Main() { 
    A a = new A(); 
    B b = new B(); 
 
    // Check to see if a can be cast to B. 
    if(a is B)  // if so, do the cast 
      b = (B) a; 
    else // if not, skip the cast 
      b = null; 
 
    if(b==null)  
      Console.WriteLine("Cast b = (B) a is NOT allowed."); 
    else 
      Console.WriteLine("Cast b = (B) a is allowed"); 
  } 
}


           
          


Demonstrate is

image_pdfimage_print

   

/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/


// Demonstrate is. 
 
using System; 
 
class A {} 
class B : A {} 
 
public class UseIs { 
  public static void Main() { 
    A a = new A(); 
    B b = new B(); 
 
    if(a is A) Console.WriteLine("a is an A"); 
    if(b is A)  
      Console.WriteLine("b is an A because it is derived from A"); 
    if(a is B)  
      Console.WriteLine("This won't display -- a not derived from B"); 
 
    if(b is B) Console.WriteLine("B is a B"); 
    if(a is object) Console.WriteLine("a is an Object"); 
  } 
}


           
          


Test is and as

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; }

     }

     // the Compressible interface is now the
     // base for ILoggedCompressible
     interface ICompressible
     {
         void Compress();
         void Decompress();
     }

     // extend ICompressible to log the bytes saved
     interface ILoggedCompressible : ICompressible
     {
         void LogSavedBytes();
     }


     // Document implements both interfaces
     class Document : IStorable, ILoggedCompressible
     {
         // 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; }
         }

         // implement ICompressible
         public void Compress()
         {
             Console.WriteLine("Implementing Compress");
         }

         public void Decompress()
         {
             Console.WriteLine("Implementing Decompress");
         }

         // implement ILoggedCompressible
         public void LogSavedBytes()
         {
             Console.WriteLine("Implementing LogSavedBytes");
         }

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


    public class TesterISAS
    {
       public void Run()
       {
           Document doc = new Document("Test Document");

           // cast using as, then test for null
           IStorable isDoc = doc as IStorable;
           if (isDoc != null)
           {
               isDoc.Read();
           }
           else
           {
               Console.WriteLine("Could not cast to IStorable");
           }



           ILoggedCompressible ilDoc = doc as ILoggedCompressible;
           if (ilDoc != null)
           {
               Console.Write("
Calling both ICompressible and ");
               Console.WriteLine("ILoggedCompressible methods...");
               ilDoc.Compress();
               ilDoc.LogSavedBytes();
           }
           else
           {
               Console.WriteLine("Could not cast to ILoggedCompressible");
           }

           // cast using as, then test for null
           ICompressible icDoc = doc as ICompressible;
           if (icDoc != null)
           {
               Console.WriteLine(
                   "
Treating the object as Compressible... ");
               icDoc.Compress();
           }
           else
           {
               Console.WriteLine("Could not cast to ICompressible");
           }
       }

       [STAThread]
       static void Main()
       {
          TesterISAS t = new TesterISAS();
          t.Run();
       }
    }
 }

           
          


Illustrates the use of the is operator

image_pdfimage_print

   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

/*
  Example3_9.cs illustrates the use of
  the is operator
*/

public class Example3_9
{

  public static void Main()
  {

    int myInt = 0;
    bool compatible = myInt is int;
    System.Console.WriteLine("myInt is int = " + compatible);

    compatible = myInt is long;
    System.Console.WriteLine("myInt is long = " + compatible);

    compatible = myInt is float;
    System.Console.WriteLine("myInt is float = " + compatible);

  }

}