#575 – Using the is Operator to Check the Type of a Reference-Typed Object
May 3, 2012 Leave a comment
You use the is operator to check whether an object (or expression) is of a particular type. It checks the dynamic type of an object at runtime to see if the object or expression is assignment compatible with the specified type.
The is operator will return true if the type matches exactly, if an implicit conversion exists, or if an explicit conversion (a cast) would succeed.
// (Terrier is a sub-class of Dog) Dog d = new Dog("Fido", 5); Terrier t = new Terrier("Jack", 17, "Crabby"); Dog d2 = t; bool check = d is Dog; // true (same type) check = d is Terrier; // false check = t is Dog; // true (implicit conversion to base class) check = t is Terrier; // true check = d2 is Dog; // true check = d2 is Terrier; // true (explicit conversion would succeed) Terrier t2 = (Terrier)d2; check = d is object; // true check = t is Cow; // false