πŸ“Œ 1. What Is Boxing?

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

  • The value gets wrapped in a heap object.

Example

int num = 42;
object obj = num; // Boxing
Console.WriteLine(obj); // 42
  • Here, the int (value type, stored on the stack) is boxed into an object on the heap.

πŸ“Œ 2. What Is Unboxing?

  • Unboxing is the reverse β€” converting an object back to a value type.

  • Requires an explicit cast, and the object must hold the correct type, otherwise an exception occurs.

Example

object obj = 42;   // Boxing
int num = (int)obj; // Unboxing
Console.WriteLine(num); // 42

⚠️ If the object doesn’t contain the right type, an InvalidCastException is thrown:

object obj = 42;
string str = (string)obj; // ❌ InvalidCastException

πŸ“Œ 3. Performance Considerations

  • Boxing is costly because:

    1. It allocates memory on the heap.

    2. Copies the value type into that memory.

  • Unboxing is costly because:

    1. It checks the object type at runtime.

    2. Copies the value back from the heap to the stack.

Example of heavy boxing (bad practice)

ArrayList list = new ArrayList();
list.Add(1);  // Boxing
list.Add(2);  // Boxing
list.Add(3);  // Boxing
 
int x = (int)list[0]; // Unboxing

βœ… Instead, use generics (List<int>) to avoid boxing:

List<int> list = new List<int> { 1, 2, 3 };
int x = list[0]; // No boxing/unboxing

πŸ“Œ 4. Summary Table

ConversionDefinitionRequires Cast?Example
BoxingValue type β†’ object (heap)Noobject o = 42;
UnboxingObject β†’ value type (stack)Yesint n = (int)o;

πŸ“Œ 5. Analogy

  • Boxing: like putting a gift inside a box β€” the value type is β€œwrapped” into an object.

  • Unboxing: like taking the gift out β€” you need to know what’s inside, otherwise you grab the wrong thing and get an error.


βœ… Summary:

  • Boxing wraps a value type into an object (implicit).

  • Unboxing extracts the value type back from the object (explicit, requires cast).

  • Avoid boxing/unboxing in performance-critical code β€” use generics instead.


πŸ‘‰ Do you want me to also cover nullable value types (int?) vs boxing in this section, or keep nullables for later when we expand on advanced types?