0
0
CsharpComparisonBeginner · 4 min read

Boxing vs Unboxing in C#: Key Differences and When to Use Each

In C#, boxing is the process of converting a value type (like int) to an object type, while unboxing extracts the value type from the object. Boxing wraps the value inside an object on the heap, and unboxing retrieves it back to the stack as the original value type.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of boxing and unboxing in C#.

AspectBoxingUnboxing
DefinitionConverting a value type to an object typeExtracting the value type from an object
Data MovementValue copied from stack to heapValue copied from heap back to stack
PerformanceSlower due to heap allocationSlower due to type checking and copying
Typical UseWhen storing value types as objectsWhen retrieving value types from objects
Error RiskNo error, always succeedsCan throw InvalidCastException if type mismatch
Example Typeint to objectobject to int
⚖️

Key Differences

Boxing happens when a value type like int, bool, or struct is converted into a reference type, specifically an object. This means the value is wrapped inside a new object on the heap, which allows it to be treated like any other object. This process involves copying the value from the stack to the heap, which adds overhead.

Unboxing is the reverse process where the value type is extracted from the object. It requires an explicit cast and includes a runtime check to ensure the object actually contains the expected value type. If the cast is incorrect, it throws an InvalidCastException. Unboxing copies the value back from the heap to the stack.

While both boxing and unboxing allow value types to be used as objects, boxing is automatic when assigning a value type to an object, but unboxing requires explicit casting. Both operations have performance costs, so minimizing their use is important in performance-critical code.

💻

Boxing Code Example

This example shows boxing by assigning an int value to an object variable.

csharp
int number = 123;
object boxedNumber = number; // Boxing happens here
Console.WriteLine(boxedNumber);
Output
123
↔️

Unboxing Equivalent

This example shows unboxing by casting the object back to an int.

csharp
object boxedNumber = 123; // Boxing
int number = (int)boxedNumber; // Unboxing
Console.WriteLine(number);
Output
123
🎯

When to Use Which

Choose boxing when you need to treat value types as objects, such as storing them in collections that hold object types. However, be aware that boxing creates a new object on the heap, which can impact performance.

Choose unboxing when you need to retrieve the original value type from an object, but always ensure the object actually contains the expected type to avoid exceptions. To improve performance, avoid unnecessary boxing and unboxing by using generics or value type collections when possible.

Key Takeaways

Boxing converts a value type to an object by copying it to the heap.
Unboxing extracts the value type from an object with an explicit cast and runtime check.
Both boxing and unboxing add performance overhead and should be minimized.
Use boxing when storing value types as objects; use unboxing to retrieve them safely.
Prefer generics to avoid boxing/unboxing in performance-sensitive code.