Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a boxed value

Tags:

c#

casting

Why can't an int that's been boxed be directly cast to double?

object o = 12;
double d = (double)o;

That throw an invalid cast exception. Instead it seems it has to first be cast as an int, and then on to double.

object o = 12;
double d = (double)(int)o;

I'm sure the simple answer is "because that's how boxing works" but I'm hoping someone might shed a bit of light here.

like image 866
Adam Rackis Avatar asked Mar 15 '11 13:03

Adam Rackis


People also ask

What is boxed value?

Boxed values are data structures that are minimal wrappers around primitive types*. Boxed values are typically stored as pointers to objects on the heap. Thus, boxed values use more memory and take at minimum two memory lookups to access: once to get the pointer, and another to follow that pointer to the primitive.

When casting from a number the value must be?

when casting from a number the value must be a number less than infinity.

What is consequence of boxing and unboxing?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.

Why do we need boxing and unboxing?

Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.


2 Answers

Check out this question from earlier today: Why am I getting InvalidCastException?

Unboxing operations only succeed if the target type is exactly the same as the original type that was boxed, so an exception is thrown. This link that John Leidegren provided explains in detail.

like image 123
Mikael Östberg Avatar answered Oct 09 '22 22:10

Mikael Östberg


If you don't know the original type at compile-time:

object o = 12;
double d = (double)Convert.ChangeType(o, typeof(double));
like image 23
Chris Xue Avatar answered Oct 09 '22 23:10

Chris Xue