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 ...
Get C# 5.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.