Free mag vol1 | Page 355

CHAPTER 8  WORKING WITH INTERFACES ***** Fun with Interfaces ***** Drawing NoName the Hexagon -> Points: 6 -> Drawing IDraw3D compatible type Drawing Hexagon in 3D! Drawing NoName the Circle -> NoName's not pointy! Drawing Joe the Triangle -> Points: 3 Drawing JoJo the Circle -> JoJo's not pointy! Interfaces As Return Values Interfaces can also be used as method return values. For example, you could write a method that takes an array of Shape objects and returns a reference to the first item that supports IPointy: // This method returns the first object in the // array that implements IPointy. static IPointy FindFirstPointyShape(Shape[] shapes) { foreach (Shape s in shapes) { if (s is IPointy) return s as IPointy; } return null; } You could interact with this method as follows: static void Main(string[] args) { Console.WriteLine("***** Fun with Interfaces *****\n"); // Make an array of Shapes. Shape[] myShapes = { new Hexagon(), new Circle(), new Triangle("Joe"), new Circle("JoJo")}; // Get first pointy item. // To be safe, you'd want to c