Information Technology Reference
In-Depth Information
That's because
ints
are value types and can never be
null
. What value of
int
should be stored in i if o is not an integer? Any value you pick might
also be a valid integer. Therefore,
as
can't be used. You're stuck using the
cast syntax. It's actually a boxing/unboxing conversion (see Item 45):
object
o =
Factory
.GetValue();
int
i =
0
;
try
{
i = (
int
)o;
}
catch
(
InvalidCastException
)
{
i =
0
;
}
Using exceptions as a flow control mechanism should strike you as a ter-
rible practice. (See Item 47.) But you're not stuck with the behaviors of
casts. You can use the
is
statement to remove the chance of exceptions or
conversions:
object
o =
Factory
.GetValue();
int
i =
0
;
if
(o
is int
)
i = (
int
)o;
If o is some other type that can be converted to an
int
, such as a
double
,
the
is
operator returns false. The
is
operator always returns false for null
arguments.
The
is
operator should be used only when you cannot convert the type
using
as
. Otherwise, it's simply redundant:
// correct, but redundant:
object o = Factory.GetObject();
MyType t = null;
if (o is MyType)
t = o as MyType;
The previous code is the same as if you had written the following:
// correct, but redundant:
object
o =
Factory
.GetObject();