Possible Duplicate:
Direct casting vs 'as' operator?
Anyone can give a comparison between as and cast?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A straight cast will fail if the object being casted is not of the type requested. An
as-cast will instead return null. For example:However:
When the object being casted is of the type you are casting to, the result is the same for either syntax: the object is successfully casted.
Note specifically that you should avoid the “as-and-invoke” pattern:
Because if the cast fails, you will throw a NullReferenceException instead of a ClassCastException. This may cause you to chase down the reason that
somethingis null, when it’s actually not! The uglier, but better codeWill throw a ClassCastException when the object referenced by
somethingcannot be converted toSomeType, and a NullReferenceException whensomethingis null.