25 Jan 2024
Boxing and unboxing in C# refer to the process of converting a value type to a reference type (boxing) and converting a boxed value back to its original value type (unboxing).
Boxing:
-
Definition: Boxing is the process of converting a value type (e.g., int, char, float) into a reference type (e.g., object).
-
This process involves creating a new object on the heap to hold the value of the value type, and copying the value from the stack to the newly allocated heap memory.
-
For example:
- Boxing an Integer:
int number = 42; // value type object boxedNumber = number; // boxing occurs Console.WriteLine($"Boxed number: {boxedNumber}");
- Boxing a Structure:
struct Point { public int X; public int Y; } Point point = new Point { X = 10, Y = 20 }; // value type (struct) object boxedPoint = point; // boxing occurs Console.WriteLine($"Boxed point: {boxedPoint}");
- Boxing a Decimal:
decimal amount = 123.45m; // value type (decimal) object boxedAmount = amount; // boxing occurs Console.WriteLine($"Boxed amount: {boxedAmount}");
Unboxing:
-
Definition: Unboxing is the process of converting a reference type (previously created by boxing) back to a value type.
-
It involves extracting the value from the boxed object and copying it back onto the stack as a value type.
-
Unboxing requires an explicit cast to the appropriate value type.
-
For example:
- Unboxing an Integer:
object boxedNumber = 42; // boxed value (object) int number = (int)boxedNumber; // unboxing occurs Console.WriteLine($"Unboxed number: {number}");
- Unboxing a Structure:
object boxedPoint = new Point { X = 10, Y = 20 }; // boxed value (object) Point point = (Point)boxedPoint; // unboxing occurs Console.WriteLine($"Unboxed point: ({point.X}, {point.Y})");
- Unboxing a Decimal:
object boxedAmount = 123.45m; // boxed value (object) decimal amount = (decimal)boxedAmount; // unboxing occurs Console.WriteLine($"Unboxed amount: {amount}");
Boxing and unboxing operations can impact performance because they involve memory allocation and copying. They are typically more expensive in terms of execution time compared to operations involving pure value types. Therefore, it's generally recommended to avoid unnecessary boxing and unboxing operations, especially in performance-sensitive code. Using generics and value types whenever possible can help minimize the need for boxing and unboxing.