What is Boxing and Unboxing in C#?
Short answer
Boxing is the process of converting a value type, such as an int, into a reference type by wrapping it inside an object, allowing it to be treated like any other reference type object, while unboxing is the reverse process of extracting that original value type back out of the…
Advertisement
AModel answer
Boxing is the process of converting a value type, such as an int, into a reference type by wrapping it inside an object, allowing it to be treated like any other reference type object, while unboxing is the reverse process of extracting that original value type back out of the object wrapper. Both operations happen automatically or through simple casting, but they carry a performance cost since boxing allocates new memory on the heap and unboxing requires a runtime type check.
int number = 42;
object boxed = number; // boxing
int unboxed = (int)boxed; // unboxingReal-world example
A legacy method that only accepts parameters of type object receives an int argument, causing it to be automatically boxed into an object, and the method later unboxes it back into an int to perform calculations.
Likely follow-ups
- Why does boxing negatively affect performance?
- How do generics help avoid unnecessary boxing and unboxing?
Related topics