Click to Rate and Give Feedback
MSDN
MSDN Library
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
C# Programming Guide
Boxing Conversion (C# Programming Guide)

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:

C#
int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

C#
object o = i;  // implicit boxing

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:

C#
int i = 123;
object o = (object)i;  // explicit boxing

This example converts an integer variable i to an object o by using boxing. Then, the value stored in the variable i is changed from 123 to 456. The example shows that the original value type and the boxed object use separate memory locations, and therefore can store different values.

C#
class TestBoxing
{
    static void Main()
    {
        int i = 123;
        object o = i;  // implicit boxing

        i = 456;  // change the contents of i

        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
*/

For more information, see the following sections in the C# Language Specification:

  • 4.3.1 Boxing Conversions

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker