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?
The as operator can only be used on reference types, it cannot be overloaded, and it will return null if the operation fails. It will never throw an exception. Casting can be used on any compatible types, it can be overloaded, and it will throw an exception if the operation fails.
Casting is also used for other conversions (e.g. between value types); "as" is only valid for reference type expressions (although the target type can be a nullable value type) Casting can invoke user-defined conversions (if they're applicable at compile-time); "as" only ever performs a reference conversion.
We cast a value by placing the targeted type in parentheses () next to the value we want to cast. C#'s compiler allows many different kinds of casting. For example, we can cast an int to a double , a char to an int , or a float to a decimal .
When the variable of one data type is changed to another data type is known as the Type Casting. According to our needs, we can change the type of data. At the time of the compilation, C# is a statically-typed i.e., after the declaration of the variable, we cannot declare it again.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With