#575 – Using the is Operator to Check the Type of a Reference-Typed Object

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
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: