Kevin
Kevin

Reputation: 5694

How does casting work?

I was wondering what C# does when you for example cast an object to an int.

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

Much appreciated :)!

Upvotes: 8

Views: 3889

Answers (4)

Marc Gravell
Marc Gravell

Reputation: 1062520

In the general case, that is a tricky one ;p It depends on the exact scenari:

  • (when the target is a value-type) if the source value is only known as object, it is an unbox operation, which reverses the special way in which value-types can be stored in an object reference (Unbox / Unbox_Any)
  • if the source type is a Nullable<int>, then the .Value property is evaluated (which can cause an exception if the value is empty)
  • if the source type is one of a few built-in types documented in the spec (uint, float, etc), then the specific opcode (which may be nothing at all) is emitted to perform the conversion directly in IL (Conv_I4)
  • if the source type has a custom implicit or explicit conversion operator defined (matching the target type), then that operator is invoked as a static method (Call)
  • (in the case of reference types) if it isn't obviously always untrue (different hierarchies), then a reference cast/check is performed (CastClass)
  • otherwise the compiler treats it as an error

I think that is fairly complete?

Upvotes: 15

Dyppl
Dyppl

Reputation: 12381

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

Upvotes: 1

Neil Knight
Neil Knight

Reputation: 48537

Take a gander here for information about : Casting

Also, worth a read : Boxing and Unboxing

Upvotes: 0

James Gaunt
James Gaunt

Reputation: 14783

This is an example of boxing and unboxing:

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

C# is taking the value type of int (perhaps it's a local variable, in a register or on the stack), boxing it up in an object, and putting it on the heap. When you cast back to int the process is reversed.

More generally the complier creates quite complex and type specific IL when casting, in particular it's got to make sure at run time that the types you are casting between are compatible, look for specific cast operators defined in your code, deal with overflows etc etc. Casting is quite an expensive process.

Upvotes: 5

Related Questions