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.
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 a number less than infinity.
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.
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.
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.
If you don't know the original type at compile-time:
object o = 12;
double d = (double)Convert.ChangeType(o, typeof(double));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With