An unboxing conversion permits a reference-type to be explicitly converted to a value-type. The following unboxing conversions exist:
- From the type
object to any value-type (including any enum-type). - From the type
System.ValueType to any value-type (including any enum-type). - From any interface-type to any value-type that implements the interface-type.
- From the type
System.Enum to any enum-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 operand must be a reference to an object that was previously created by boxing a value of that value-type. If the source operand is null, a System.NullReferenceException is thrown. If the source operand is a reference to an incompatible object, a System.InvalidCastException is thrown.