Information Technology Reference
In-Depth Information
The is Operator
As shown previously, some conversion attempts are not successful, and raise an
InvalidCastException
exception at run time. Instead of blindly attempting a conversion, you
can use the
is
operator to check whether a conversion would complete successfully.
The syntax of the
is
operator is the following, where
Expr
is the source expression:
Returns a bool
↓
Expr
is
TargetType
The operator returns
true
if
Expr
can be successfully converted to the target type through
any of the following:
A reference conversion
A boxing conversion
An unboxing conversion
For example, in the following code, you use the
is
operator to check whether variable
Bill
of type
Employee
can be converted to type
Person
, and then take the appropriate action.
class Employee : Person { }
class Person {
public string Name = "Anonymous";
public int Age = 25;
}
class Program {
static void Main()
{
Employee Bill = new Employee();
Person p;
// Check if variable Bill can be converted to type Person
if( Bill is Person ) {
p = Bill;
Console.WriteLine("Person Info: {0}, {1}", p.Name, p.Age);
}
}
}
The
is
operator can only be used for reference conversions and boxing and unboxing con-
versions. It
cannot
be used for user-defined conversions.