Difference between Boxing and Unboxing in C# programming.


C# provides two methods to link value type to reference type and vice e Versa. These two methods for linking are named boxing and unboxing where Boxing is used for the conversion of the value type to an object type while Unboxing refers to the conversion of the object type to the value type.

The following are the important differences between Boxing and Unboxing.

Sr. No.KeyBoxingUnboxing
1ImplementationBoxing made object type referred to as the value type.Unboxing basically processes the retrieving value from the boxed object.
2StorageIn the case of boxing, the value stored on the stack is copied to the object stored on heap memory.On the other hand in case of unboxing the object's value stored on the heap memory is copied to the value type stored on the stack.
3Type of conversionBoxing in general known as implicit conversion.Unboxing refers to the explicit conversion.

Example of Boxing vs Unboxing

JavaTester.java

 Live Demo

public class JavaTester {
   public static void main(String[] args){
      int val = 119;
      // Boxing
      Object o = val;
      // Change the value of val
      val = 120;
      //unboxing
      int x = (int)o;
      System.out.println("Value of x is {0}"+ x);
      System.out.println("Value type of val is {0}"+val);
      System.out.println("Object type of val is {0}"+o);
   }
}

Output

Value of x is {0}119
Value type of val is {0}120
Object type of val is {0}119

Updated on: 17-Sep-2019

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements