ECMA-334: 11.3.2 Unboxing conversions
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Language Specification |
|
| © 2006 ECMA International |
11.3.2 Unboxing conversions
An unboxing conversion permits an explicit conversion from object or System.ValueType to any non-nullable-value-type or from any interface-type to any non-nullable-value-type that implements the interfacetype.
Furthermore, there is an explicit unboxing conversion from System.Enum to any enumeration 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.
A nullable-type T? has unboxing conversions from the same set of types as T. An unboxing conversion
permits an explicit conversion from object or System.ValueType to any nullable-type or from any
interface-type to any nullable-type whose underlying type implements the interface-type. Furthermore, there
is an explicit unboxing conversion from System.Enum to any nullable-type whose underlying type is an
enumeration type. An unboxing conversion to a nullable-type T? is processed as follows:
- If the source is a null reference, the result is a null value of type
T?.
- If the source is a reference to a boxed
T, the result is aT?produced by unboxing and wrapping the source.
- Otherwise, a
System.InvalidCastExceptionis thrown.
Referring to the imaginary boxing class described in the previous subclause, an unboxing conversion of an
object box to a value-type T consists of executing the expression ((T_Box)box).value. [Example: 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;
end example]
For an unboxing conversion to a given value-type to succeed at run-time, the value of the source operand
shall 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.