Boxing and Unboxing (C# Programming Guide)
This page is specific to:.NET Framework Version:
C# Programming Guide
Boxing and Unboxing (C# Programming Guide)

Updated: July 2009

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. In the following example, the integer variable i is boxed and assigned to object o.

int i = 123;
object o = (object)i;  // boxing


The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int)o;  // unboxing


Performance

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally. For more information, see Performance.

Boxing

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:

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:

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


Description

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.

Example

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


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.

Unboxing

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:

  • Checking the object instance to make sure that it is a boxed value of the given value type.

  • Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:

int i = 123;      // a value type
object o = i;     // boxing
int j = (int)o;  // unboxing


The following figure demonstrates the result of the previous statements.

Unboxing Conversion

UnBoxing Conversion graphic

For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.

C# Language Specification

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

  • 4.3.1 Boxing Conversions

Related Sections

For more information:

C# Language Specification

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

  • 4.3 Boxing and Unboxing

See Also

Concepts

Change History

Date

History

Reason

July 2009

Added information about exceptions to "Unboxing" section.

Customer feedback.

July 2008

Consolidated previously separate boxing and unboxing topics into this topic.

Content bug fix.

Community Content

Good, but where is the INTENT and REAL-WORLD scenario
Added by:EGH25091970
Ok, the article is fair. But to really understand this where is the WHY or INTENT along with a good real-world example to ultimately get the point across?

-- seems pretty obvious to me. Maybe they should put the bit about EXPENSIVE in 40 foot high flaming letters for the hard of understanding.
What is the Goal ?
Added by:JoséPeña
I have clear how works the boxing and unboxing about the value types, implemented interfaces, and moreover how the value is treated in memory, copied the whole value to the heap, but for that should be consider this ?

For nothing makes sense if you do not give this REAL-WORLD sample as NoEgo states ? For me this page still has no sense without REAL-WORLD situation.


Boxing Sample using PowerShell
Added by:Thomas Lee
# Test-boxing1.ps1
# MSDN Sample recoded in PowerShell
# thomas lee - tfl@psp.co.uk
[int] $i= 123 
[object] $o=$i 
$i= 456;
"The value-type value = {0}" -f $i
"The object-type value = {0}" -f$ o

This script produces the following output:

PS C:\Users\tfl> . 'C:\Users\tfl\AppData\Local\Temp\Untitled1.ps1'
The value-type value = 456
The object-type value = 123
Real world scenario of boxing and un boxing
Added by:mbegley

Boxing and unboxing are particularly useful in cases where we would like to use the ThreadPool class provided by .Net.
ThreadPool.QueueUserWorkItem() method allows us to queue up a method for execution on a thread pool thread. The method to be executed by the thread pool thread must be passed in as parameter to the "QueueUserWorkItem" as an instance of "WaitCallback" delegate. WaitCallback instance can reference any method that takes in a single parameter, of type "object". (The definition of WaitCallback is public delegate void WaitCallback(object state)).

Say, we have a method to be executed on the ThreadPool thread, named "Worker", and our logic inside the worker requires an integer value for its processing.
We would define our method to accept a parameter as "object", so that it can be referenced as an instance of WaitCallback delegate.
The definition of the method would go as follows:

  public void Worker(object parameter)
{
if (parameter is int){
  
      
int retrievedValue = (int)parameter;
// Use the retrieved value for further processing
}
}


The method that queues up the "Worker" method for execution on the thread pool thread would look something as below:

  public void Queuer()
{
  int valueToBePassed = 10;
// Some logic that might alter valueToBePassed
ThreadPool.QueueUserWorkItem(new WaitCallback(Worker), valueToBePassed);

}


Since "WaitCallback" delegate requires our "Worker" method to accept a single parameter of type object, the caller implicitly boxes the value type variable named "valueToBePassed" into an "object".

When the parameter is received by the "Worker" method, it first checks if the parameter received as type "object" indeed boxes an integer, and then explicitly un boxes it using an explicit cast, and then uses the value for its further processing.

This is one real world scenario where boxing and unboxing are useful.

The previous example is awesome
Added by:atarikg
Thanks for the real world example. Actually when coming to explaining the codes, microsoft sucks about giving real world examples and why we would need to use a specific feature they provide. If I don't know where to use it, How can I know where I will need that feature.

So thanks for the example above, Ram Kumar C.

Aaron.
© 2010 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View