π 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:
-
It allocates memory on the heap.
-
Copies the value type into that memory.
-
-
Unboxing is costly because:
-
It checks the object type at runtime.
-
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
Conversion | Definition | Requires Cast? | Example |
---|---|---|---|
Boxing | Value type β object (heap) | No | object o = 42; |
Unboxing | Object β value type (stack) | Yes | int 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?