Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 218
Michael Stum Avatar asked Aug 05 '08 15:08

Michael Stum


People also ask

Should I use as or <> to cast?

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.

What is difference between casting and as C#?

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.

How do I cast an object to a type in C#?

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 .

What is type casting in C# with example?

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.


2 Answers

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

like image 140
Rytmis Avatar answered Oct 05 '22 23:10

Rytmis


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.

like image 33
denny Avatar answered Oct 06 '22 00:10

denny