Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - How is explicit cast with "as" different (internally) from (someType)someobject, and why?

I understand that when you use an explicit cast like this:

(someType)someobject

you can get an invalid cast exception if someobject is not really someType.

As well I understand that when you cast with as like this:

myObject = someObject as someType

myObject is just rendered null if someObject isn't really someType.

How are these evaluated differently and why?

like image 621
richard Avatar asked Feb 21 '11 07:02

richard


People also ask

How do implicit and explicit casting differ?

Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.

What is cast operator in C#?

Cast, in the context of C#, is a method by which a value is converted from one data type to another. Cast is an explicit conversion by which the compiler is informed about the conversion and the resulting possibility of data loss.


1 Answers

John Skeet has a C# faq where he explains the differences between the two operators. See paragraph 'What's the difference between using cast syntax and the as operator?'.

Quote :

Using the as operator differs from a cast in C# in three important ways:

  1. It returns a null when the variable you are trying to convert is not of the requested type or in its inheritance chain, instead of throwing an exception.
  2. It can only be applied to reference type variables converting to reference types.
  3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions).

like image 61
Sem Vanmeenen Avatar answered Sep 27 '22 18:09

Sem Vanmeenen