static void Main(string[] args) { // One way to implement polymorphism is through an abstract class Console.WriteLine("We created an interface, but never used it in this example"); Shape rect = new Rectangle(5, 5); Shape tri = new Triangle(5, 5); Console.WriteLine("Rect Area " + rect.area()); Console.WriteLine("Trit Area " + tri.area()); // Using the overloaded + on 2 Rectangles Rectangle combRect = new Rectangle(5, 5) + new Rectangle(5, 5); Console.WriteLine("combRect Area = " + combRect.area()); Console.Write("Hit Enter to Exit"); string exitApp = Console.ReadLine(); }
static void Main(string[] args) { Invoice iv = new Invoice(new object[] { "object", "object" }); iv.SaveToPDF(); iv.SaveToWord(); Shape triangle = new Triangle(); // Watch Shape type here! // triangle.CallMethod(); won't compile // 1 try { Triangle tr = (Triangle)triangle; // use cast to get an access to interface tr.CallMethod(); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } // 2 Triangle tr2 = triangle as Triangle; // Will give null on unsucessful cast if (tr2 != null) { tr2.CallMethod(); } else { Console.WriteLine("No interface here."); } // 3 if (triangle is ISimple) { ((Triangle)triangle).CallMethod(); } else { Console.WriteLine("No interface here."); } }