
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
144
|
Chapter 3: Classes and Structures
This expression returns a Boolean value: true if the cast will succeed or false if the
cast will fail. For example:
if (SpecificObj is Base)
{
// It is of type Base.
}
else
{
// Cannot cast SpecificObj to a Base type object.
}
Never use the is operator with a user-defined conversion (either
explicit or implicit). The
is operator always returns false when used
with these types of conversions, regardless of whether the cast can be
performed.
This operator does not work with user-defined conversions (both explicit and
implicit). Unlike the
as operator, a compile-time error will not be displayed; instead,
the
is operator will always return false. This operator should never be used with
user-defined conversions, since the result will always be in question. Also, unlike the
as operator, the is operator will work with unboxing conversions.
The following code determines whether an unboxing operation can be performed:
// An int is passed in to this method and boxed.
public void SomeMethod(object o)
{
if (o is int)
{
// o can be unboxed.
// It is now possible to cast o to an int.
int x = (int)o;
}
else
{
// Cannot unbox o.
}
}
This code first declares an integer variable x and boxes it into an object variable o.
The
is operator is then used to determine whether o can ...