Pages

Men

rh

6/16/2012

Boxing and Unboxing in C#

Boxing and Unboxing:
Boxing:
  • Converting value type to reference Type.
  • Boxing Supports Implicit and Explicit  conversion
  • Boxing 20 times costlier than normal initialization, because  when ever boxing is done the following tasks will be performed instantly.
  • Runtime will search for respective data with the stack
  • A copy of value is made into Heap.
  • Reference to this copy is maintained from the object variable.
Example:
               int i = 123;
               object o = (object)i;  // boxing
 
Unboxing:
  • Converting reference type to value type.
  • Unboxing supports Explicit conversion.
  • Unboxing is 4 times costlier than normal initialized because, when unboxing is made following tasks are performed internally.
  • Object referenced value is searched within the heap.
  • A copy of this is made into stack.
Example:
               o = 123;
               i = (int) o; // unboxing
 
When to use Boxing and Unboxing :
Use only  if necessary, but we should use Boxing and Unboxing in case of other operations are costlier than Boxing and unboxing.

No comments :

Post a Comment