Boxing and Unboxing
Understand the cost of converting to object.
Boxing and Unboxing is a free C# Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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);
}
}What Is Unboxing?
Unboxing extracts the value type back out of the box with an explicit cast. The cast type must match the boxed type exactly.
using System;
class Program
{
static void Main()
{
object o = 42; // boxing
int n = (int)o; // unboxing
Console.WriteLine("Unboxed: " + n);
}
}Unboxing Requires the Right Type
You must unbox to the exact original type. Unboxing to a different type throws InvalidCastException.
using System;
class Program
{
static void Main()
{
object o = 100;
try
{
long wrong = (long)o; // InvalidCastException at runtime
Console.WriteLine(wrong);
}
catch (InvalidCastException)
{
Console.WriteLine("Must unbox to int, not long");
}
}
}Boxing Makes a Copy
Boxing copies the value. Changing the original afterward does not change the boxed copy.
using System;
class Program
{
static void Main()
{
int n = 1;
object o = n; // box copies 1
n = 99;
Console.WriteLine("original=" + n + ", boxed=" + o);
}
}The Cost of Boxing
Each box allocates heap memory and adds garbage-collection pressure. In hot loops this overhead can hurt performance significantly.
using System;
class Program
{
static void Main()
{
// Each iteration boxes an int -> many heap allocations
object sumBox = 0;
for (int i = 0; i < 5; i++)
{
int current = (int)sumBox + i;
sumBox = current; // box again
}
Console.WriteLine("Result: " + sumBox);
}
}Avoiding Boxing with Generics
Generic collections like List<int> store value types without boxing, unlike the old non-generic ArrayList.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
var list = new List<int>(); // no boxing
list.Add(1);
list.Add(2);
int first = list[0]; // no unboxing
Console.WriteLine("First: " + first);
}
}Boxing with Interfaces
Assigning a struct to an interface variable also boxes it, because the interface reference must point to a heap object.
using System;
class Program
{
static void Main()
{
int n = 7;
IComparable c = n; // boxing to interface
Console.WriteLine(c.CompareTo(10));
}
}Detecting Boxed Types
You can check a boxed object type at runtime with is before unboxing safely.
using System;
class Program
{
static void Main()
{
object o = 3.5;
if (o is double d)
Console.WriteLine("It is a double: " + d);
else
Console.WriteLine("Not a double");
}
}Boxing in String Concatenation
Concatenating a value type with strings can box it. Using interpolation or ToString is often clearer, though boxing here is usually negligible.
using System;
class Program
{
static void Main()
{
int count = 3;
string msg = "Count is " + count; // count is converted
Console.WriteLine(msg);
}
}Putting It Together
Boxing bridges value and reference worlds but costs allocations. Prefer generics to avoid it, and unbox to the exact type with a safe check.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
object boxed = 256;
if (boxed is int value)
Console.WriteLine("Safely unboxed: " + value);
var noBox = new List<int> { 1, 2, 3 };
Console.WriteLine("Generic count: " + noBox.Count);
}
}Quick Check
Test your understanding of boxing and unboxing.
Recap
Boxing wraps a value type in a heap object (e.g. object o = 5;); unboxing extracts it with an explicit cast to the exact original type. Boxing copies the value and allocates memory, adding GC pressure. Prefer generic collections like List<int> to avoid boxing, and use is for safe unboxing.
using System;
class Program
{
static void Main()
{
object boxed = 42; // box
int n = (int)boxed; // unbox
Console.WriteLine(n);
}
}Frequently asked questions
Is the “Boxing and Unboxing” lesson free?
Yes — the full text of “Boxing and Unboxing” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Boxing and Unboxing”?
Understand the cost of converting to object. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Boxing and Unboxing” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.