Information Technology Reference
In-Depth Information
object
o =
Factory
.GetObject();
// Version one:
MyType
t = o
as
MyType
;
if
(t !=
null
)
{
// work with t, it's a MyType.
}
else
{
// report the failure.
}
Or, you could write this:
object
o =
Factory
.GetObject();
// Version two:
try
{
MyType
t;
t = (
MyType
)o;
// work with T, it's a MyType.
}
catch
(
InvalidCastException
)
{
// report the conversion failure.
}
Yo u ' l l a g r e e t h a t t h e fi r s t v e r s i o n i s s i m p l e r a n d e a s i e r t o r e a d . I t d o e s n o t
have the
try
/
catch
clause, so you avoid both the overhead and the code.
Notice that the cast version must check
null
in addition to catching excep-
tions.
null
can be converted to any reference type using a cast, but the
as
operator returns
null
when used on a
null
reference. So, with casts, you
need to check
null
and catch exceptions. Using
as
, you simply check the
returned reference against
null
.
The biggest difference between the
as
operator and the
cast
operator is
how user-defined conversions are treated. The
as
and
is
operators exam-
ine the runtime type of the object being converted; they do not perform
any other operations. If a particular object is not the requested type or is