CHAPTER 8 WORKING WITH INTERFACES
IPointy itfPt2 = hex2 as IPointy;
}
if(itfPt2 != null)
Console.WriteLine("Points: {0}", itfPt2.Points);
else
Console.WriteLine("OOPS! Not pointy...");
Console.ReadLine();
Notice that when you use the as keyword, you have no need to use try/catch logic, given that if the
reference is not null, you know you are calling on a valid interface reference.
Obtaining Interface References: The is Keyword
You may also check for an implemented interface using the is keyword (also first discussed in Chapter
6). If the object in question is not compatible with the specified interface, you are returned the value
false. On the other hand, if the type is compatible with the interface in question, you can safely call the
members without needing to use try/catch logic.
To illustrate, assume we have an array of Shape types containing some members that implement
IPointy. Notice how we are able to determine which items in the array support this interface using the is
keyword, as shown in this retrofitted Main() method:
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")} ;
for(int i = 0; i < myShapes.Length; i++)
{
// Recall the Shape base class defines an abstract Draw()
// member, so all shapes know how to draw themselves.
myShapes[i].Draw();
// Who's pointy?
if(myShapes[i] is IPointy)
Console.WriteLine("-> Points: {0}", ((IPointy) myShapes[i]).Points);
else
Console.WriteLine("-> {0}\'s not pointy!", myShapes[i].PetName);
Console.WriteLine();
}
290
}
Console.ReadLine();