Free mag vol1 | Page 301

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM } } The short answer is that you can now make the assumption that anything deriving from Shape does indeed have a unique version of the Draw() method. To illustrate the full story of polymorphism, consider the following code: static void Main(string[] args) { Console.WriteLine("***** Fun with Polymorphism *****\n"); // Make an array of Shape-compatible objects. Shape[] myShapes = {new Hexagon(), new Circle(), new Hexagon("Mick"), new Circle("Beth"), new Hexagon("Linda")}; } // Loop over each item and interact with the // polymorphic interface. foreach (Shape s in myShapes) { s.Draw(); } Console.ReadLine(); Here is the output from the modified Main() method: ***** Fun with Polymorphism ***** Drawing Drawing Drawing Drawing Drawing NoName the Hexagon NoName the Circle Mick the Hexagon Beth the Circle Linda the Hexagon This Main() method illustrates polymorphism at its finest. Although it is not possible to directly create an instance of an abstract base class (the Shape), you are able to freely store references to any subclass with an abstract base variable. Therefore, when you are creating an array of Shapes, the array can hold any object deriving from the Shape base class (if you attempt to place Shape-incompatible objects into the array, you receive a compiler error). Given that all items in the myShapes array do indeed derive from Shape, you know they all support the same “polymorphic interface” (or said more plainly, they all have a Draw() method). As you iterate over the array of Shape references, it is at runtime that the underlying type is determined. At this point, the correct version of the Draw() method is invoked in memory. This technique also makes it very simple to safely extend the current hierarchy. For example, assume you derived more classes from the abstract Shape base class (Triangle, Square, etc.). Due to the polymorphic interface, the code within your foreach loop would not have to change in the slightest, as the compiler enforces that only Shape-compatible types are placed within the myShapes array. 238