O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The is and as Operators

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 List 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

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 is and the as operators .

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 ( myObject is ICompressible )

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.[9]

The as operator tries to cast the object to the type, and if an exception would be thrown, it instead returns null:

    ICompressible myCompressible = myObjectas ICompressible
    if ( myCompressible != null )

Warning

The is operator is slightly ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required