
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining a Variable’s Type with the is Operator
|
143
public void CreateAndHandlePoint( )
{
// Create a new point object and return it.
object retObj = CreatePoint(PointTypeEnum.Point2D);
// Handle the point object based on its actual type.
if (retObj is ExPoint2D)
{
Console.WriteLine("Use the ExPoint2D type");
}
else if (retObj is ExPoint3D)
{
Console.WriteLine("Use the ExPoint3D type");
}
else if (retObj is Point2D)
{
Console.WriteLine("Use the Point2D type");
}
else if (retObj is Point3D)
{
Console.WriteLine("Use the Point3D type");
}
else
{
Console.WriteLine("Invalid point type");
}
}
Notice that the tests for the ExPoint2D and ExPoint3D objects are performed before
the tests for
Point2D and Point3D. This order will allow you to differentiate between
base classes and their derived classes (
ExPoint2D derives from Point2D and ExPoint3D
derives from Point3D). If you had reversed these tests, the test for Point2D would eval-
uate to
true for both the Point2D class and its derivatives (ExPoint2D).
Discussion
The is operator is a fast and easy method of predetermining whether a cast will
work. If the cast fails, you have saved yourself the overhead of trying the cast and
handling a thrown exception. If the
is operator determines that this cast can success-
fully be performed, all you ...