Reputation: 5694
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
Reputation: 1062520
In the general case, that is a tricky one ;p It depends on the exact scenari:
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
)Nullable<int>
, then the .Value
property is evaluated (which can cause an exception if the value is empty)uint
, float
, etc), then the specific opcode (which may be nothing at all) is emitted to perform the conversion directly in IL (Conv_I4
)Call
)CastClass
)I think that is fairly complete?
Upvotes: 15
Reputation: 12381
In this particular case it's called "unboxing", check http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
Upvotes: 1
Reputation: 48537
Take a gander here for information about : Casting
Also, worth a read : Boxing and Unboxing
Upvotes: 0
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