|
|||||
|
Boxing and unboxing is a essential concept in C#s type system. It enables a unified view of the type system where a value of any type can be treated as an object. Conversion of a value type to a reference type is called Boxing. It is possible to call object methods on any value, this holds true even for values of primitive types such as int. For e.g., the following converts an int value to an object and back again to int : int i = 1; When an object box is cast back to its original value type, the value is copied out of the box and put into the appropriate storage location. The dynamic type of a boxed value of typeT is T itself. For example, int i = 1; would print 'Obj is an int' on the screen. A boxing conversion effectively makes a copy of the value being boxed. This is different from a conversion of a reference-type to type object, in which the value continues to reference the same instance. Boxing a value of a value-type consists of allocating an object instance and copying the value-type value into that instance. For example for any value-type T, the boxing class would be declared as follows: class boxT
{
T value;
T_Box(T val) {
value = val;
}
}
An unboxing conversion permits an explicit conversion from type object to any value-type or from any interface-type to any value-type that implements the interface-type. For example : object obj = 1; uses an explicit conversion of the object 'obj' to 'int'. For an unboxing conversion to a given value-type to succeed at
run-time, the value of the source argument must be a reference to an
object that was previously created by boxing a value of that value-type.
If the source argument is null or a reference to an incompatible object,
an InvalidCastException is thrown. |