Boxing Conversions
All C# types, including the value types, are derived from type
Lets see following code sample:
This code produces the following output:
object
. Value types, however, are efficient, lightweight types that do not, by default,
include their object component in the heap. When the object component is needed, however, you can use boxing, which is an implicit conversion that takes a value
type value, creates from it a full reference type object in the heap, and returns a reference to the object.
For example
int i = 12; object oi = null; oi = i;
line 1 and 2: | declare and initialize value type variable i and reference type variable oi . |
line 3: | assign the value of variable i to oi . But oi is a reference type variable and must be assigned a reference to
an object in the heap and variable i is a value type and doesn’t have a reference to an object in the heap.
The system therefore boxes the value of i by doing the following:
|
Boxing Creates a Copy
A common misconception about boxing is that it acts upon the item being boxed. It doesn’t. It returns a reference type copy of the value. After the boxing procedure, there are two copies of the value—the value type original and the reference type copy—each of which can be manipulated separately.Lets see following code sample:
int i = 10; // Create and initialize value type object oi = i; // Create and initialize reference type Console.WriteLine("i: " + i + ", io: " + oi); i = 12; oi = 15; Console.WriteLine("i: " + i + ", io: " + oi);
This code produces the following output:
i: 10, io: 10
i: 12, io: 15
i: 12, io: 15
The Boxing Conversions
Following figure shows the boxing conversions. Any value type ValueTypeS can be implicitly converted to any of types object,System.ValueType
, or
InterfaceT
, if ValueTypeS
implements InterfaceT
.
Unboxing Conversions
Unboxing is the process of converting a boxed object back to its value type.
This code produces the following output:
Attempting to unbox a value to a type other than the original type raises an
- Unboxing is an explicit conversion.
- The system performs the following steps when unboxing a value to
ValueTypeT
:- It checks that the object being unboxed is actually a boxed value of type
ValueTypeT
. - It copies the value of the object to the variable.
- It checks that the object being unboxed is actually a boxed value of type
static void Main() { int i = 10; object oi = i; int j = (int) oi; Console.WriteLine("i: " + i + ", oi: " + oi + ", j: " + j); }
i: 10, oi: 10, j: 10
Attempting to unbox a value to a type other than the original type raises an
InvalidCastException
exception.
0 comments:
Post a Comment