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: ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.