/* safe type casting in C# (and Java) */ using System; interface IA { void f(); } class A : IA { public virtual void f() { Console.WriteLine("I'm A.f"); } } class AA : A, IA { public override void f() { Console.WriteLine("I'm AA.f"); } } class AB : A, IA { public override void f() { Console.WriteLine("I'm AB.f"); } // the following will allow casting from AB object to AA object. public static explicit operator AA(AB m) { AA x = new AA(); // define algorithm to create AA object from BB object. return x; } // now AB n = new AB(); AA m = (AA)n; will work } public class casting { public static void Main() { /* the following will cause a compile-time error AA a1 = new AA(); AB a2 = (AB)a1; // siblings cannot cross-cast */ /* the following will compile OK, but cause runtime error IA aa, ab; aa = new AA(); ab = (AB)aa; // throws casting exception at runtime */ // both examples above will compile in traditional C++, // with unpredicatable (meaningless) runtime behavior. /* the following casting code is OK */ IA a, aa; aa = new AA(); a = (A)aa; a.f(); // prints AA.f (because of override keyword) // AA a2 = (AA)a; Also ok. } }