Boxing and Unboxing


In the C# unified type system, a value of any type can be treated as an object. This is made possible by the concept of boxing and unboxing.

Boxing

  • It is the process of converting a value type to an object.
  • CLR puts the value inside a System.Object instance, which is then stored on the managed heap.
  • Boxing is implicit.
Example
public void Boxing()
{
    int x = 100;
    object obj = x; // x is boxed into obj
}

Unboxing

  • It is the process of extracting a value type from an object.
  • Unboxing is explicit.
Example
public void UnBoxing()
{
    object obj = 100;
    int x = (int)obj; // obj is unboxed into x
}

Back to Notes