Search

Boxing in C#

Boxing is used to store value types in the garbage-collected heap. 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 type allocates an object instance on the heap and copies the value into the new object.
Consider the following declaration of a value-type variable:
The following statement implicitly applies the boxing operation on the variable i:
int i = 123;



// Boxing copies the value of i into object o. 
object o = i;



The result of this statement is creating an object reference 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

BoxingConversion graphic
It also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:
int i = 123;
object o = (object)i;  // explicit boxing




Example:
class TestBoxing
{
static void Main()
{
int i = 123;

// Boxing copies the value of i into object o. 
object o = i;  

// Change the value of i.
i = 456;  

// The change in i does not effect the value stored in o.
System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}
/* Output:
The value-type value = 456
The object-type value = 123
*/



The following example demonstrates a case of invalid unboxing and the resulting InvalidCastException. Using try and catch, an error message is displayed when the error occurs.
class TestUnboxing
{
static void Main()
{
int i = 123;
object o = i;  // implicit boxing 

try
{
int j = (short)o;  // attempt to unbox

System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
}
}
This program outputs:
Specified cast is not valid. Error: Incorrect unboxing.
If you change the statement:
int j = (short) o;
to
int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing OK.