Boxing and Unboxing
Understand the cost of converting to object.
What Is Boxing?
Boxing wraps a value type inside an object so it can be treated as a reference type. object o = 5; boxes the int onto the heap.
using System;
class Program
{
static void Main()
{
int n = 5;
object o = n; // boxing
Console.WriteLine("Boxed value: " + o);
}
}Why Boxing Happens
Boxing occurs whenever a value type is assigned to a variable of type object (or an interface). The runtime allocates a heap box holding a copy of the value.
using System;
class Program
{
static void Main()
{
double d = 3.14;
object boxed = d; // boxing copies d into a heap object
Console.WriteLine(boxed);
}
}