Boxing: Boxing is a process of converting value type into reference type.
Unboxing: Unboxing is a process of converting reference type to value type.
In .NET, boxing and unboxing are concepts related to the conversion between value types and reference types.
- Boxing: Boxing is the process of converting a value type to an object type (reference type) compatible with the Object class or any interface type implemented by this value type. When you box a value type, a new object is allocated on the heap to hold the value, and the value is copied into that object. For example:
int intValue = 10;
object obj = intValue; // Boxing occurs here
In this example, the integer value intValue
is boxed into an object obj
.
- Unboxing: Unboxing is the process of extracting the value type from the object. It’s the reverse operation of boxing. Unboxing requires an explicit cast from the object type to the value type. For example:
object obj = 10; // Boxing occurs here
int intValue = (int)obj; // Unboxing occurs here
In this example, the integer value is first boxed into an object, and then it’s unboxed back into an integer.
It’s important to note that boxing and unboxing operations incur performance overhead because they involve memory allocation and copying. Therefore, excessive boxing and unboxing operations should be avoided in performance-sensitive code.
In summary, boxing converts a value type to a reference type (object), and unboxing retrieves the value type from the reference type.