Boxing

Difference between Boxing and Unboxing in C#

Boxing

  • The first two lines of code declare and initialize value type variable i and reference type variable oi.
  • In the third line of code, you want to assign the value of variable i to oi. But oi is a reference type variable and must be assigned a reference to an object in the heap.
  • Variable i, however, is a value type and doesn’t have a reference to an object in the heap.
  • The system therefore box the value of i by doing the following:

    • Creating an object of type int in the heap
    • Copying the value of i to the int object
    • Returning the reference of the int object to oi to store as its reference

    Memory is allocated on the heap that will contain the value type’s data and the other overhead necessary to make the object look like
    every other instance of a managed object of reference type .
    The value of the value type is copied from its current storage location into the newly allocated location on the heap.
    The result of the conversion is a reference to the new storage location on the heap.

    Unboxing

    What is UnBoxing Conversion?

    Unboxing is the process of converting a boxed object back to its value type.Unboxing is an explicit conversion.

    The system performs the following steps when unboxing a value to ValueTypeT:

    It checks that the object being unboxed is actually a boxed value of type ValueTypeT.
    It copies the value of the object to the variable.