Information Technology Reference
In-Depth Information
Boxing Creates a Copy
A common misunderstanding about boxing is that it somehow 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.
For example, the following code shows the separate manipulation of each copy of the
value. Figure 18-23 illustrates the code.
The first line defines value type variable i and initializes its value to 10 .
￿
The second line creates reference type variable oi and initializes it with the boxed copy
of variable i .
￿
The last three lines of code show i and oi being manipulated separately.
￿
int i = 10; // Create and initialize value type
Box i and return the reference to oi.
object oi = i; // Create and initialize reference type
Console.WriteLine("i: {0}, io: {1}", i, oi);
i = 12;
oi = 15;
Console.WriteLine("i: {0}, io: {1}", i, oi);
This code produces the following output:
i: 10, io: 10
i: 12, io: 15
Figure 18-23. Boxing creates a copy that can be manipulated separately
Search WWH ::




Custom Search