public void cast_error() { // cast will pass compiler, but result a runtime error if wrong cast // e.g. cast Frank to Hexgan, (Hexgan)frant object frank = new Manager(); Hexagon hex; try { hex = (Hexagon) frank; } catch (InvalidCastException ex) { Console.WriteLine( ex.Message); } }
public void as_operator () { // trail cast, if not compatible, return null // Use "as" to test compatability. object[] things = new object[ 4]; things[ 0] = new Hexagon(); things[ 1] = false; things[ 2] = new Manager(); things[ 3] = "Last thing"; foreach (object item in things) { Hexagon h = item as Hexagon; if (h == null) Console.WriteLine(" Item is not a hexagon"); else { h.Draw(); } } }