Boxing and Unboxing in C#
Boxing and unboxing allow developers to convert value types to reference types and vice versa. These operations can reduce performance due to additional calculations, such as allocating memory for a new object and copying data.
Boxing
Boxing occurs when a value type is converted to the System.Object, System.Enum, System.ValueType, or interface type. This operation can be explicit or implicit:
int a = 10;
object b = a; // Implicit boxing
object c = (object)a; // Explicit boxing
Implicit boxing occurs when we use a value-type variable where a reference type is expected. Let's look at the examples of such operations:
- calling a method with reference-type parameters and value-type arguments;
- calling methods of the base reference type of value-type instances;
- declaring a reference-type variable with initialization of a value-type instance.
You can find some detailed examples below.
Example 1
struct Point : IComparable<Point>
{
....
public int CompareTo(Point point) { .... }
}
static void
ProcessComparableItems<T>(IComparable<T> lhs,
IComparable<T> rhs)
{ .... }
static int Calculate(....)
{
var firstPoint = new Point(....);
var secondPoint = new Point(....);
ProcessComparableItems(firstPoint, secondPoint);
....
}
The ProcessComparableItems method handles two IComparable<T> parameters. At the same time, the Point structure implements this interface. However, if we call the ProcessComparableItems method with arguments of the Point type, each of them is boxed:
// ProcessComparableItems(firstPoint, secondPoint);
IL_0039: ldloc.0
IL_003a: box BoxingTest.Program/Point // <=
IL_003f: ldloc.1
IL_0040: box BoxingTest.Program/Point // <=
IL_0045: call void
BoxingTest.Program::ProcessComparableItems
<valuetype BoxingTest.Program/Point>(....)
....
Example 2
var dateTime = new DateTime(....);
Type typeInfo = dateTime.GetType();
dateTime is a variable of the (DateType) value type. The GetType method of dateTime, defined in the System.Object type, is called. To call the method, we need to perform boxing of the dateTime object:
// Type typeInfo = dateTime.GetType();
IL_0014: ldloc.0
IL_0015: box [System.Runtime]System.DateTime // <=
IL_001a: call instance class
[System.Runtime]System.Type
[System.Runtime]System.Object::GetType()
....
Unboxing
Unboxing is the conversion of a boxed reference type back to a value type. Unboxing has some peculiarities:
- Unboxing must be done to exactly the same data type that was boxed. Unboxing to an incompatible value type causes an InvalidCastException.
- Attempting to unbox a null reference causes a NullReferenceException.
Example:
double a = 1;
object b = a;
int c = (int)b;
Unboxing a variable to an incompatible value type causes InvalidCastException. Here is the fixed code:
int c = (int)(double)b;
0