#576 – Using the is Operator with Value Typed Objects

You can use the is operator to check the type of value-typed objects.  The result of a check using the is operator is true if the type of the expression matches the specified type exactly.  Because value types don’t support inheritance, an object of one type will never return true for the is operator on a different type, even if the value is assignment compatible with the specified type.

bool check;

byte b = 1;
short s = 2;

check = b is byte;     // true
check = b is short;    // false

// Assignment succeeds
s = b;        // short <= byte

check = s is short;    // true
check = s is byte;     // false

Because all value types inherit from System.ValueType and, indirectly, from System.Object, the is operator always returns true when checking against these types.

check = b is object;   // true
check = s is object;   // true
check = b is System.ValueType;   // true
check = s is System.ValueType;   // true
Advertisements

#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

#448 – Use the is Operator to See if an Object Implements an Interface

We saw that we could use the as operator to cast an object to a variable of a particular interface type.  If the object’s type does not implement the interface, the as operator returns null.

            IMoo viaMoo = objSomething as IMoo;
            if (viaMoo != null)
                viaMoo.Moo();

You can also use the is operator to first check to see if an object’s class implements a particular interface.

        private static void MooIfYouCan(object mooCandidate)
        {
            IMoo viaMoo;
            if (mooCandidate is IMoo)
            {
                viaMoo = (IMoo)mooCandidate;
                viaMoo.Moo();
            }
        }

We can pass any object into this method and the IMoo.Moo method will be called only if the object implements the IMoo interface.

            Cow bossie = new Cow("Bossie", 12);
            object mooer = bossie;
            MooIfYouCan(mooer);

            mooer = new Dog("Bert", 5);
            MooIfYouCan(mooer);