Free mag vol1 | Page 351

CHAPTER 8  WORKING WITH INTERFACES // Call Points property defined by IPointy. Hexagon hex = new Hexagon(); Console.WriteLine("Points: {0}", hex.Points); Console.ReadLine(); } This approach works fine in this particular case, given that you are well aware that the Hexagon type has implemented the interface in question and, therefore, has a Points property. Other times, however, you might not be able to determine which interfaces are supported by a given type. For example, suppose you have an array containing 50 Shape-compatible types, only some of which support IPointy. Obviously, if you attempt to invoke the Points property on a type that has not implemented IPointy, you would receive an error. So how can you dynamically determine if a class or structure supports the correct interface? One way to determine at runtime whether a type supports a specific interface is to make use of an explicit cast. If the type does not support the requested interface, you receive an InvalidCastException. To handle this possibility gracefully, use structured exception handling as in the following example: static void Main(string[] args) { ... // Catch a possible InvalidCastException. Circle c = new Circle("Lisa"); IPointy itfPt = null; try { itfPt = (IPointy)c; Console.WriteLine(itfPt.Points); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } Console.ReadLine(); } While you could use try/catch logic and hope for the best, it would be ideal to determine which interfaces are supported before invoking the interface members in the first place. Let’s see two ways of doing so. Obtaining Interface References: The as Keyword You can determine whether a given type supports an interface by using the as keyword, introduced in Chapter 6. If the object can be t &VFVB2F