Sunday, September 27, 2015

Boxing and Unboxing

Boxing: Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.
  1.          It converts a value type into a reference type.
  2.          Values are stored in the Stack first then moved to the heap.
  3.          Creates a container/box for holding the value.



Unboxing: Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.
  1.          It is the opposite process of boxing.
  2.          It converts an object type back into the value type.
  3.          It is an explicit operation using C-style casting.

Example
namespace BoxingUnboxing
{
    class Program
    {
        static void Main(string[] args)
        {
            int Val = 1;
            Object Obj = Val;          //Boxing
            int i = (int)Obj;          //Unboxing
            Console.WriteLine("Boxing: {0}", Obj);
            Console.WriteLine("Unboxing: {0}", i);
            Console.ReadLine();
        }
    }
}
Note:
Sometimes boxing is necessary, but you should avoided it if possible, since it will slow down the performance and increase memory requirements.


For example, when a value type is boxed, a new reference type is created and the value is copied from the value type to the newly created reference type. This process takes time and required extra memory (around twice the memory of the original value type).


No comments:

Post a Comment