How does casting work?

I was wondering what C # does when you, for example, apply object to int .

 object o = 10; int i = (int) o; 

Very much appreciated :)!

+6
casting c #
source share
4 answers

In general, this is a difficult task, p depends on the exact scenario:

  • (if the target is a value type), if the original value is known only as object , this is an unbox operation that changes the special way that type values ​​are stored in an object link ( Unbox / Unbox_Any )
  • If the source type is Nullable<int> , then .Value is evaluated (which may throw an exception if the value is empty)
  • if the source type is one of several built-in types documented in the specification ( uint , float , etc.), then a specific operation code (which may do nothing at all) is emitted to perform the conversion directly to IL ( Conv_I4 )
  • If the source type has a custom implicit or explicit conversion operator defined (corresponding to the target type), then this operator is called as a static method ( Call )
  • (in the case of reference types), if this is not always always incorrect (different hierarchies), then reference casting / checking is CastClass ( CastClass )
  • otherwise the compiler treats it as an error

I think this is pretty complete?

+11
source share

This is an example of boxing and unboxing:

http://msdn.microsoft.com/en-us/library/yz2be5wk (VS.80) .aspx

C # takes an int value type (maybe it's a local variable, in a register or on a stack), boxing it in an object and putting it in a heap. When you return to int, the process reverses.

More generally, the compiler creates a rather complex and specific type of IL during casting, in particular, it must make sure that at run time the types that you execute are compatible, look for specific casting operators defined in your code, handle overflows and etc. Casting is a rather expensive process.

+4
source share

In this particular case, it is called "unboxing", check http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

+1
source share

Take a gander here for information on: Casting

Also worth reading: Boxing and Unboxing

0
source share

All Articles