Conversions of Classes (Reference Types) to an Interface the Object Might Implement : Cast : Class C# Examples


C# Examples » Class » Cast »

 

Conversions of Classes (Reference Types) to an Interface the Object Might Implement









    
using  System;

interface  Printable
{
        string  Print();
}
class  NonPrintablePaper
{
        public  NonPrintablePaper(int  value)
        {
                this.value  =  value;
        }
        public  override  string  ToString()
        {
                return(value.ToString());
        }
        int  value;
}
class  PrintablePaper:  Printable
{
        public  PrintablePaper(string  name)
        {
                this.name  =  name;
        }
        public  override  string  ToString()
        {
                return(name);
        }
        string  Printable.Print()
        {
                return("print...");
        }
        string  name;
}
class  MainClass
{
        public  static  void  TryPrinting(params  object[]  arr)
        {
                foreach  (object  o  in  arr)
                {
                        Printable  printableObject  =  o  as  Printable;
                        if  (printableObject  !=  null)
                        Console.WriteLine("{0}",  printableObject.Print());
                        else
                        Console.WriteLine("{0}",  o);
                }
        }
        public  static  void  Main()
        {
                NonPrintablePaper  s  =  new  NonPrintablePaper(13);
                PrintablePaper  c  =  new  PrintablePaper("Tracking  Test");
                TryPrinting(s,  c);
        }
}
    
   
  
   



Output

13
print...


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Class
» Cast