13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11 TypesBoxing classes like T_Box and int_Box above don’t actually exist and the dynamic type of a boxed valueisn’t actually a class type. Instead, a boxed value of type T has the dynamic type T, and a dynamic typecheck using the is operator can simply reference type T. [Example: For example,int i = 123;object box = i;if (box is int) {Console.Write("Box contains an int");}will output the string “Box contains an int” on the console. end example]A boxing conversion implies making a copy of the value being boxed. This is different from a conversion ofa reference-type to type object, in which the value continues to reference the same instance and simply isregarded as the less derived type object. [Example: For example, given the declarationstruct Point{public int x, y;public Point(int x, int y) {this.x = x;this.y = y;}}the following statementsPoint 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 assignmentof p to box causes the value of p to be copied. Had Point been declared a class instead, the value 20would be output because p and box would reference the same instance. end example]11.3.2 Unboxing conversionsAn unboxing conversion permits an explicit conversion from type object to any value-type or from anyinterface-type to any value-type that implements the interface-type. An unboxing operation consists of firstchecking that the object instance is a boxed value of the given value-type, and then copying the value out ofthe instance.Referring to the imaginary boxing class described in the previous section, an unboxing conversion of anobject box to a value-type T consists of executing the expression ((T_Box)box).value. [Example: Thus,the statementsobject box = 123;int i = (int)box;conceptually correspond toend example]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 operandmust be a reference to an object that was previously created by boxing a value of that value-type. If thesource operand is null a System.NullReferenceException is thrown. If the source operand is areference to an incompatible object, a System.InvalidCastException is thrown.97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!