c# - the comparison between as and cast -
possible duplicate:
direct casting vs 'as' operator?
anyone can give comparison between , cast?
a straight cast fail if object being casted not of type requested. as
-cast instead return null. example:
object obj = new object(); string str = (string)obj; // throws classcastexception
however:
object obj = new object(); string str = obj string; // sets str null
when object being casted is of type casting to, result same either syntax: object casted.
note should avoid "as-and-invoke" pattern:
(something sometype).foo();
because if cast fails, throw nullreferenceexception instead of classcastexception. may cause chase down reason something
null, when it's not! uglier, better code
((sometype)something).foo();
will throw classcastexception when object referenced something
cannot converted sometype
, , nullreferenceexception when something
null.
Comments
Post a Comment