CHAPTER 8 WORKING WITH INTERFACES
Figure 8-3. The updated shapes hierarchy
If you now define a method taking an IDraw3D interface as a parameter, you can effectively send in
any object implementing IDraw3D. (If you attempt to pass in a type not supporting the necessary interface,
you receive a compile-time error.) Consider the following method defined within your Program class:
// I'll draw anyone supporting IDraw3D.
static void DrawIn3D(IDraw3D itf3d)
{
Console.WriteLine("-> Drawing IDraw3D compatible type");
itf3d.Draw3D();
}
We could now test whether an item in the Shape array supports this new interface, and if so, pass it
into the DrawIn3D() method for processing:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Interfaces *****\n");
Shape[] myShapes = { new Hexagon(), new Circle(),
new Triangle(), new Circle("JoJo") } ;
for(int i = 0; i < myShapes.Length; i++)
{
...
// Can I draw you in 3D?
if(myShapes[i] is IDraw3D)
DrawIn3D((IDraw3D)myShapes[i]);
}
}
Here is the output of the updated application. Notice that only the Hexagon object prints out in 3D,
as the other members of the Shape array do not implement the IDraw3D interface.
292