Friday, 20 February 2015

Boxing and Unboxing in C#

Welcome to Logically Proven Blog.
This post demonstrates boxing and unboxing in C#.

C# type system has two varieties of data types: value type and reference type.

Value type: built-in data types like int, long, bool or user-defined structures (struct)
Reference type: string, array, objects (classes) etc.,

Let me ask you one question here - is int[] (array of integers) a value type or a reference type?

Array is a single collection of several items. Microsoft .NET CLR (Common Language Runtime) states that all array types are reference types. All arrays are implicitly derived from System.Array which itself derived from System.Object. This means all arrays are reference types.

It is very important to know how C# manages data and memory.

A value type stores its contents is allocated in a memory called the stack.
A reference type, such as an instance of an class or an array, is allocated in a memory called the heap.

For example:  int i = 123;  //allocates on stack
    TestClass obj = new TestClass(); //allocates instance of a class on heap


Boxing is the process of converting a value type to the object type or to any interface type implemented by this value type. When we boxes a value type, the CLR (Common Language Runtime) wraps it inside a System.Object type and stores it on the managed heap (copies the value into the new object which is allocated on a heap).


By default, the boxing process is an implicit conversion.

int i = 123;
// The following line boxes i. 
object o = i;  

Explciit boxing is an optional. But it is never required.

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

Changing the value type has no effect on boxed value type.

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


Unboxing is a reverse process of boxing means converting an object type to a value type or from an interface type of a value type that implements the interface. Unboxing is an explicit conversion.

An unboxing operation consists of -

Checking the object instance to make sure that it is a boxed value of a given type.
Copying the value from the instance into the value-type variable.


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

Possible exceptions while working with unboxing:

While we are working with unboxing operation there is a possiblity of NullReferenceException and InvalidCastException

NullReferenceException: Attempting to unbox null causes an NullReferenceException.
InvalidCastException: Attempting to unbox a reference to an incompatible value type causes an InvalidCastExcpetion.

Example demonstrating InvalidCastException:

class TestUnboxing
    static void Main()
        int i = 123;
        object o = i;  // implicit boxing 

            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);

//output: Specified cast is not valid. Error: Incorrect unboxing.
//correct statement is int j=(int)o;


It is best to avoid using value types in situations where they must be boxed a high number of times. Boxing and unboxing are computationally expensive process (boxing has to create a new object, this can take up to 20 times longer than a simple reference assignment and unboxing takes 4 times as long as an assignment).

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically proven
Learn, Teach, Share

Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things.


Post a Comment