Saturday, February 27, 2016

OOPS : Understanding Boxing and Unboxing in C#

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.

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.
Boxing and Unboxing

For Example

  1. // int (value type) is created on the Stack
  2. int stackVar = 12;
  3.  
  4. // Boxing = int is created on the Heap (reference type)
  5. object boxedVar = stackVar;
  6.  
  7. // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
  8. int unBoxed = (int)boxedVar;

Real Life Example

  1. int i = 10;
  2. ArrayList arrlst = new ArrayList();
  3.  
  4. //ArrayList contains object type value
  5. //So, int i is being created on heap
  6. arrlst.Add(i); // Boxing occurs automatically
  7.  
  8. int j = (int)arrlst[0]; // Unboxing occurs

Note

  1. 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).
  2. Attempting to unbox a null causes a NullReferenceException.
    1. int? stackVar = null;
    2. // Boxing= Integer is created on the Heap
    3. object boxedVar = stackVar;
    4.  
    5. // NullReferenceException
    6. int unBoxed = (int)boxedVar; //Object reference not set to an instance of an object.
  3. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
    1. int stackVar = 12;
    2. // Boxing= Integer is created on the Heap
    3. object boxedVar = stackVar;
    4.  
    5. // InvalidCastException
    6. float unBoxed = (float)boxedVar; //Specified cast is not valid.

No comments:

Post a Comment