Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value of a value allocates an object instance and copies the value into the new object.
Consider the following declaration of a value-type variable:
int i = 123;
The following statement implicitly applies the boxing operation on the variable i
:
object o = i;
The result of this statement is creating an object o
, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i
. The difference between the two variables, i
and o
, is illustrated in the following figure.
Boxing Conversion
It also possible, but never needed, to perform the boxing explicitly as in the following example:
int i = 123; object o = (object) i;
This example converts an integer variable i
to an object o
via boxing. Then the value stored in the variable i
is changed from 123
to 456
. The example shows that the object keeps the original copy of the contents, 123
.
// Boxing an integer variable using System; class TestBoxing { public static void Main() { int i = 123; object o = i; // Implicit boxing i = 456; // Change the contents of i Console.WriteLine("The value-type value = {0}", i); Console.WriteLine("The object-type value = {0}", o); } }
The value-type value = 456 The object-type value = 123