Casting: (NewType) vs. Object as NewType

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."


Also note that you can only use the as keyword with a reference type or a nullable type

ie:

double d = 5.34;
int i = d as int;

will not compile

double d = 5.34;
int i = (int)d;

will compile.

Tags:

C#

.Net