X hits on this document





95 / 396


struct Point { public int x, y;

public Point(int x, int y) { this.x = x; this.y = y; } }

the following statements

Point p = new Point(10, 10); object box = p; p.x = 20; Console.Write(((Point)box).x);

will output the value 10 on the console because the implicit boxing operation that occurs in the assignment of p to box causes the value of p to be copied. Had Point been declared a class instead, the value 20 would be output because p and box would reference the same instance.

4.3.2 Unboxing conversions

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.

82Copyright Microsoft Corporation 1999-2003. All Rights Reserved.

Document info
Document views459
Page views459
Page last viewedSun Oct 23 03:46:50 UTC 2016