Csharp/CSharp Tutorial/Class/cast
Conversions of Classes (Reference Types) to an Interface the Object Might Implement
<source lang="csharp">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); }
}</source>
13 print...
Conversions of Classes (Reference Types) To the Base Class of an Object
<source lang="csharp">using System; public class Base {
public virtual void talk() { Console.WriteLine("Base"); }
} public class Derived: Base {
public override void talk() { Console.WriteLine("Derived"); }
} public class Test {
public static void Main() { Derived d = new Derived(); Base b = d; b.talk(); Derived d2 = (Derived) b; object o = d; Derived d3 = (Derived) o; }
}</source>
Derived