0Pricing
C# Academy · Lesson

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);
    }
}

All lessons in this course

  1. Value Types vs Reference Types
  2. Boxing and Unboxing
  3. Implicit and Explicit Conversions
  4. The Convert Class and Parsing
← Back to C# Academy