An unboxing conversion permits an explicit conversion from type object
to any value-type or from any interface-type to any value-type that implements the interface-type. An unboxing operation consists of first checking that the object instance is a boxed value of the given value-type, and then copying the value out of the instance.
Referring to the imaginary boxing class described in the previous section, an unboxing conversion of an object box
to a value-type T
consists of executing the expression ((T_Box)box).value
. Thus, the statements
object box = 123; int i = (int)box;
conceptually correspond to
object box = new int_Box(123); int i = ((int_Box)box).value;
For an unboxing conversion to a given value-type to succeed at run-time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value-type. If the source argument is null
or a reference to an incompatible object, an InvalidCastException
is thrown.