Monday, September 10, 2012

Boxing and Unboxing in C#


Boxing is implicit conversion. The Main purpose of Boxing is used to convert value types into reference type or object type and store in the heap.

     Example: int i = 1;

Boxing a value type allocates an object instance on the heap and copies the value into the new object. 

     Example: // 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.

It also possible to perform the boxing explicitly as in the following 

Example, but explicit boxing is never used.

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


public class TestBoxing
    public static void Main()
        int i = 1;
        // Boxing copies the value of i into object o. 
        object o = i;  
        // Change the value of i.
        i = 4;  
        // The change in i does not effect the value stored in o.
        Console.WriteLine("The value-type value =", i);
        Console.WriteLine("The object-type value =", o);
/* Output:
    The value-type value = 4
    The object-type value = 1


Unboxing is an explicit conversion. The Main purpose of Un-Boxing is used to convert the object type or reference type to a value type and store in the stack.

                                 int i = 1;       // a value type 
                       object o = i;    // boxing (implicit conversion)
                       int j = (int)o;  // Unboxing (explicit conversion) 


No comments: