Boxing is the process of converting a value type to the type object, and unboxing is extracting the value type from the object. While the boxing is implicit, unboxing is explicit.
Example (written in C#):
int i = 13;
object myObject = i; // boxing
i = (int)myObject; // unboxing
In .NET interviews, explaining the difference between boxing and unboxing is essential. Here’s the correct answer along with an example:
Boxing: Boxing is the process of converting a value type (such as an int or a struct) to a reference type (such as object). When a value type is boxed, it is allocated on the heap rather than the stack. This is necessary when you want to treat a value type as an object, such as when passing it to a method that accepts parameters of type object.
Example of boxing:
int i = 10;
object obj = i; // Boxing occurs here
In this example, the integer variable i
is boxed into an object reference obj
. Now, obj
holds a reference to the boxed copy of i
on the heap.
Unboxing: Unboxing is the process of converting a reference type (such as object) to a value type. It’s the reverse of boxing, where a value type is extracted from the object. This operation requires an explicit cast.
Example of unboxing:
object obj = 10;
int i = (int)obj; // Unboxing occurs here
In this example, the object obj
contains a boxed integer. By explicitly casting obj
to an int, unboxing occurs, and the value type is extracted from the object and stored in the variable i
.
It’s important to note that boxing and unboxing operations can have performance implications, especially if done frequently in performance-sensitive code, as they involve memory allocations and type conversions. It’s generally advisable to minimize boxing and unboxing operations where possible.