What is actually the difference between these two casts?
SomeClass sc = (SomeClass)SomeObject; SomeClass sc2 = SomeObject as SomeClass;
Normally, shouldn’t they both be explicit casts to the specified type?
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.
The former will throw an exception if the source type can’t be cast to the target type. The latter will result in sc2 being a null reference, but no exception.
[Edit]
My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it’s not the only one. Other differences include:
And finally, using ‘as’ vs. the cast operator, you’re also saying ‘I’m not sure if this will succeed.’