There may be times, however, in which you do not know at
compile time whether or not an object supports a particular interface.
For instance, given a
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.
Any time you see casting, you must question the design of the program. It is common for casting to be the result of poor or lazy design. That said, there are times that casting is unavoidable, especially when dealing with nongeneric collections that you did not create.
You could cast each member blindly to
ICompressible, and then catch the exception
that will be thrown for those that are not
ICompressible, but this is ugly, and there are
two better ways to do so: the
as operators .
is operator lets you query
whether an object implements an interface (or derives from a base
class). The form of the
if ( myObject is ICompressible )
is operator evaluates true
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 tries to cast
the object to the type, and if an exception would be thrown, it instead
ICompressible myCompressible = myObject
asICompressible if ( myCompressible != null )
is operator is slightly ...