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.
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
as operators provide a much better way.
is operator lets you query whether an object implements an interface (or derives from a base class). The form of the
is operator is:
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.
as operator is similar to
is, but it goes a step further. The
as operator tries ...