C sharp - Boxing and Unboxing in C#

Boxing and unboxing are concepts related to value types and reference types in C#.

What is Boxing?

Boxing is the process of converting a value type (like int, float, bool) into a reference type, specifically into an object.

Example:

int num = 42;
object obj = num;  // Boxing
  • Here, the integer num is boxed into the object variable obj.

  • A copy of the value is placed on the heap, and the reference is stored in obj.

What is Unboxing?

Unboxing is the process of extracting the value type from the object.

Example:

object obj = 42;
int num = (int)obj;  // Unboxing
  • You need to explicitly cast during unboxing.

  • If the cast fails (wrong type), it throws an InvalidCastException.

Complete Example:

int num = 100;           // Value type
object boxed = num;      // Boxing

int unboxed = (int)boxed;  // Unboxing
Console.WriteLine(unboxed); // Output: 100