In C#, boxing, and unboxing are mechanisms used to convert value types (such as int, double, and bool) to reference types (such as an object) and vice versa. Here’s a brief explanation of each:
Boxing in C#
Boxing is the process of converting a value type to a reference type. When you box a value type, a new object is created on the heap and the value of the value type is copied into that object. The original value type variable is now a reference to the newly created object.
int i = 10; // value type
object obj = i; // boxing - converting i to a reference type
Note that unboxing can only be done if the original boxed value was of the correct value type. If not, an InvalidCastException will be thrown at runtime.
Unboxing in C#
Unboxing is the process of converting a reference type back to a value type. When you unbox a reference type, the value of the boxed value type is copied back into a new value type variable. The reference type variable now refers to this new value type variable.
int i = 10; // value type
object obj = i; // boxing - converting i to a reference type
int j = (int)obj; // unboxing - converting obj back to a value type
Note that unboxing can only be done if the original boxed value was of the correct value type. If not, an InvalidCastException will be thrown at runtime.
Boxing and unboxing can have performance implications, particularly if they are done frequently in performance-critical code. This is because creating objects on the heap can be expensive in terms of memory allocation and garbage collection. Therefore, it’s generally a good idea to avoid boxing and unboxing unless it’s absolutely necessary.
using System;
class Program
{
static void Main()
{
int value = 42; // Value type
// Boxing: Converting value type to reference type
object boxedValue = value;
// Unboxing: Converting reference type back to value type
int unboxedValue = (int)boxedValue;
Console.WriteLine("Original value: " + value);
Console.WriteLine("Boxed value: " + boxedValue);
Console.WriteLine("Unboxed value: " + unboxedValue);
}
}