Information Technology Reference
In-Depth Information
Boxing Conversions
All C# types, including the value types, are derived from type 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 con-
version 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, Figure 18-22 shows three lines of code.
The first two lines of code declare and initialize value type variable i and reference type
variable oi .
￿
In the third line of code, you want to assign the value of variable i to oi . But oi is a refer-
ence type variable, and must be assigned a reference to an object in the heap. Variable i ,
however, is a value type, and does not have a reference to an object in the heap.
￿
The system therefore boxes the value of i by
-
￿
Creating an object of type int in the heap
Copying the value of i to the int object
-
Returning the reference of the int object to oi to store as its reference
-
Figure 18-22. Boxing creates a full reference type object from a value type
Search WWH ::




Custom Search