O'Reilly logo

C# 5.0 Unleashed 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

The is Operator

Casts, as described previously, should be used only if you’re absolutely sure that the object can be converted to the specified type. If it can’t, a runtime exception occurs. In effect, think about this exception as the absolute latest time where a typing error can be caught: Face it, you have a bug.

So, what if we’re just interested in knowing whether an object has a particular runtime type? In other words, we want to make a runtime type check, essentially resulting in a Boolean truth value. This is what the is operator is all about:

object o = "Bart";bool isString = o is string; // truebool isInt    = o is int;    // false

The is operator is concerned only with types and considers type hierarchies as part of its operation. For ...

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