What are Boxing and Unboxing?

Boxing and Unboxing is a concept of C#, which enables a unified view of the type system to treat the value of any type as an object.

Boxing and unboxing are concepts in the .NET framework related to the conversion between value types and reference types. Here’s the breakdown:

  1. Boxing: Boxing is the process of converting a value type to an object type. In .NET, value types are stored on the stack, whereas reference types are stored on the heap. When a value type needs to be treated as an object, such as when adding it to a collection that only accepts objects (like ArrayList or List<object>), it needs to be boxed. Boxing involves creating a new object on the heap and copying the value type’s value into that object. This allows the value type to be treated as a reference type.

    Example:

    csharp
    int i = 42;
    object obj = i; // Boxing occurs here
  2. Unboxing: Unboxing is the opposite process of boxing. It involves extracting the value type from the object. This operation requires a type conversion because the runtime must ensure that the value type being unboxed matches the expected type. Unboxing is performed explicitly using casting.

    Example:

    csharp
    object obj = 42;
    int i = (int)obj; // Unboxing occurs here

In summary, boxing and unboxing are mechanisms provided by the .NET framework to enable the interoperability between value types and reference types. However, they can have performance implications, particularly in scenarios where boxing and unboxing are done frequently, as they involve memory allocations and type checks.