Interview frequency: …
Short answer
Boxing converts a Value Type into an object on the Heap with additional memory allocation, while Unboxing extracts the original value; repeated use burdens the Garbage Collector and slows performance.
Explanation
When assigning a primitive such as int to an object variable or an interface, the CLR allocates a new object on the Heap and copies the value into it (Boxing). When retrieving it as (int)obj, the type is checked and the value is copied again (Unboxing). Generics, such as List<int> instead of the older ArrayList, eliminate this overhead entirely.
Code example
int val = 42;
object boxed = val; // Boxing: Allocate a new object on the Heap
int unboxed = (int)boxed; // Unboxing: Type-check and extract the valueCommon mistakes
- Using non-generic interfaces such as IList with thousands of numeric values, generating millions of unnecessary Boxing operations.