Conversions of Classes (Reference Types) to an Interface the Object Might Implement : cast « Class « C# / CSharp Tutorial






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);
    }
}
13
print...








7.30.cast
7.30.1.Conversions of Classes (Reference Types) to an Interface the Object Might Implement
7.30.2.Conversions of Classes (Reference Types) To the Base Class of an Object