About This eBook by Bart De Smet

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

O'Reilly logo

The as Operator

You might wonder why I made all that fuss about the underlying implementation of the is operator. Well, as you’ve seen, the is operator actually performs a cast underneath the covers and checks the result against null to determine whether the cast succeeded. Contrast this with the behavior of the cast expression that throws an InvalidCastException in case of a failed cast. Clearly, both cast mechanisms are useful.

This brings us to the as operator, which is the gentle equivalent to the cast expression: Instead of throwing an exception on failure to cast, it simply returns null. In the previous example where we dispatched types using the is operator, we actually did things rather inefficiently. First we carried out a type check: ...

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