The is and as Operators
Sometimes, however, you may not know at compile time whether an object supports a particular interface. For instance, if you have an array of IStorable
objects, you might not know whether any given object in the collection also implements ICompressible
(some do, some do not). Let’s set aside the question of whether this is a good design, and move on to how we solve the problem.
Warning
Anytime you see casting, you can question the design of the program. It is common for casting to be the result of poor or lazy design. That being said, sometimes casting is unavoidable, especially when dealing with collections that you did not create. This is one of those situations where experience over time will help you tell good designs from bad.
You could try casting each member blindly to ICompressible
. If the object in question doesn’t implement ICompressible
, an error will be raised. You could then handle that error, using techniques we’ll explain in Chapter 16. That’s a sloppy and ineffective way to do it, though. The is
and as
operators provide a much better way.
The is
operator lets you query whether an object implements an interface (or derives from a base class). The form of the is
operator is:
if (expression
is
type
)
The is
operator evaluates true if the expression
(which must be a reference type, such as an instance of a class) can be safely cast to type
without throwing an exception.
The as
operator is similar to is
, but it goes a step further. The as
operator tries ...
Get Learning C# 3.0 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.