Boxing and Unboxing in C#

Boxing

Any type value or reference can be assigned to an object without an explicit conversion. When
the compiler finds a value type where it needs a reference type, it creates an object BOX into
which it places the value.

Example

int m = 10;
object om = m;
// creates a box and hold m inot it

We can also do that through casting

int m = 10;
object om = (object)m;
//C style casting

Unboxing

  • It is opposite process of boxing.
  • It converts object type back into the value type.
  • It is an explicit operation using c style casting.

Example

int m = 10;
object om = m;
int m = (int)om;