Unboxing conversions. An unboxing conversion permits a reference-type to be explicitly converted to a value-type
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. · From the type System.ValueType to any value-type. · From any interface-type to any non-nullable-value-type that implements the interface-type. · From any interface-type to any nullable-type whose underlying type implements the interface-type. · From the type System.Enum to any enum-type. · From the type System.Enum to any nullable-type with an underlying enum-type. Note that an explicit conversion to a type parameter will be executed as an unboxing conversion if at run-time it ends up converting from a reference type to a value type (§6.2.6). An unboxing operation to a non-nullable-value-type consists of first checking that the object instance is a boxed value of the given non-nullable-value-type, and then copying the value out of the instance. Unboxing to a nullable-type produces the null value of the nullable-type if the source operand is null, or the wrapped result of unboxing the object instance to the underlying type of the nullable-type otherwise. 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 ((Box<T>)box).value. Thus, the statements object box = 123; conceptually correspond to object box = new Box<int>(123); For an unboxing conversion to a given non-nullable-value-type to succeed at run-time, the value of the source operand must be a reference to a boxed value of that non-nullable-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. For an unboxing conversion to a given nullable-type to succeed at run-time, the value of the source operand must be either null or a reference to a boxed value of the underlying non-nullable-value-type of the nullable-type. If the source operand is a reference to an incompatible object, a System.InvalidCastException is thrown.
|