Casting: (NewType) vs. Object as NewType

Possible Duplicate:
Casting vs using the 'as' keyword in the CLR

What is actually the difference between these two casts?

SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;

Normally, they should both be explicit casts to the specified type?

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.


My original answer is certainly the most pronounced difference, but as Eric Lippert points out, it's not the only one. Other differences include:

  • You can't use the 'as' operator to cast to a type that doesn't accept 'null' as a value
  • You can't use 'as' to convert things, like numbers to a different representation (float to int, for example).

And finally, using 'as' vs. the cast operator, you're also saying "I'm not sure if this will succeed."

The parenthetical cast throws an exception if the cast attempt fails. The "as" cast returns null if the cast attempt fails.

They'll throw different exceptions.
() : NullReferenceException
as : InvalidCastException
Which could help for debugging.

The "as" keyword attempts to cast the object and if the cast fails, null is returned silently. The () cast operator will throw an exception immediately if the cast fails.

"Only use the C# "as" keyword where you are expecting the cast to fail in a non-exceptional case. If you are counting on a cast to succeed and are unprepared to receive any object that would fail, you should use the () cast operator so that an appropriate and helpful exception is thrown."

For code examples and a further explanation: