#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