Casting: (NewType) vs. Object as NewType [duplicate]

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:

  • 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.”

Leave a Comment