C# Boxing vs Unboxing: How They Affect Performance
Understand how C# boxing and unboxing work, why boxing can add allocations, and how to reduce unnecessary conversions in performance-sensitive code.

Boxing and unboxing are fundamental C# operations that convert between value types (like int, bool, and struct) and reference types (like object). They are sometimes necessary, but they can also introduce hidden allocations and CPU overhead in hot paths. This article explains how they work, why unboxing can fail, and how to minimize their performance impact.
The key difference between boxing and unboxing is direction: boxing wraps a value type into a reference type (usually object or an interface it implements), while unboxing extracts the original value from that box. Boxing always creates a new object on the managed heap; unboxing copies the value back to a value-type variable. Both operations are implicit in many C# constructs, so developers often use them without noticing.
The Mechanics of Boxing and Unboxing
When you box a value type, the runtime allocates a new object on the managed heap and copies the value into it. The resulting reference points to that object. The same is true when you convert a value type to an interface it implements: the value is boxed and the interface reference points to the box. Unboxing does the reverse: it checks the type of the boxed object and copies the value back to a value-type variable.
int number = 42;
object boxed = number; // Boxing happens here
int unboxed = (int)boxed; // Unboxing happens hereAllocation is the primary cost. The new object lives until garbage collection reclaims it, adding pressure to the GC. Unboxing is cheaper than boxing because it is only a copy and a type check, but the type check can fail if the cast is invalid.
When Does Boxing Occur Automatically?
Boxing is not limited to explicit casts to object. It also occurs whenever you pass a value type to a parameter typed as object, ValueType, or an interface. For example:
static void PrintObject(object value)
{
Console.WriteLine(value);
}
PrintObject(100); // BoxingString interpolation and composite formatting can also box on older .NET compilation paths, where the value is passed to a method that accepts object. Modern C# interpolated string handlers can avoid boxing for value types, so check the target framework and generated code rather than assuming every interpolation allocates.
int count = 5;
string s = $"Count: {count}";Collections that store object (like ArrayList from System.Collections) box every value type you add. The generic List<T> avoids this for value types because it stores them without conversion.
Unboxing and InvalidCastException
Unboxing only succeeds if the boxed value is exactly the right type. A common mistake is to cast to a related but different type:
object boxed = 42;
long value = (long)boxed; // InvalidCastExceptionYou must cast back to the exact value type that was boxed (or to the nullable form of that type). This strictness comes from the runtime's type check during unboxing. To avoid exceptions, use is or pattern matching before casting, or use as with a nullable value type.
Performance Implications of Boxing
Boxing allocates on the heap and creates garbage that must be collected. In tight loops, this can become measurable. Consider how many times a simple loop can implicitly box:
for (int i = 0; i < 1000; i++)
{
string s = "Value: " + i; // Allocates a new string AND boxes i
}Each iteration boxes i, allocating a separate object. Over thousands of iterations, that is thousands of extra allocations. Unboxing also has a small cost, but the real problem is boxing allocations.
The severity depends on how frequently the code runs. In application startup or configuration code, a few boxes do not matter. In a high-frequency request path or real-time rendering loop, they can add noticeable GC pressure.
Practical Ways to Avoid Boxing
The simplest fix is to use generics instead of non-generic collections. List<int> stores values directly, while ArrayList boxes each element. Similarly, Dictionary<TKey, TValue> with value-type keys and values avoids boxing compared to Hashtable.
List<int> numbers = new List<int>();
numbers.Add(42); // No boxingCheck the overloads you call. Many common methods have typed overloads; for example, Console.WriteLine(int) does not box. Boxing occurs when a value type is passed to a parameter typed object or an interface. Calling Console.WriteLine(value.ToString()) avoids boxing but creates an extra string, so it is not always cheaper depending on context.
Overloads that take object should be avoided when you control both sides, because passing a value type to such a parameter forces a box.
Real-World Example: JSON Serialization
JSON serializers often accept object for values, which can cause boxing when serializing value types. Some serializers optimize by using generics or Type converters, but the default reflection-based path may still box. If you are writing your own serializer for a performance-critical scenario, accept the value type as a generic parameter:
static string SerializeValue<T>(T value) where T : struct
{
// Use T directly, no boxing
return value.ToString();
}This avoids the conversion to object entirely.
Compatibility and Maintainability
Boxing is not inherently wrong; it is a language feature that enables polymorphism and loose coupling. The problem is when it appears unintentionally inside loops or repeated operations. In code review, look for hidden boxes: passing value types to object parameters, using non-generic collections, or concatenating value types into strings with +.
One maintainability concern is that boxing can hide type errors. An ArrayList can hold any type, so you might insert a string where an int is expected, and the error appears much later at unboxing. Generic counterparts catch this at compile time.
When Boxing Is Unavoidable
Sometimes you must box because you are calling an API that only accepts object—for example, a legacy method or a reflection-based function. In such cases, do the boxing once and reuse the boxed reference if possible, rather than re-boxing the same value repeatedly:
int status = 200;
object statusBox = status; // One box
// Use statusBox in multiple calls
Handle(statusBox);
Handle(statusBox);If you cannot avoid boxing, at least limit its scope.
Differences Between .NET Framework and .NET Core
The general rules hold on all modern .NET runtimes, but garbage collection tuning and allocation patterns differ slightly. On .NET (Core) with Server GC, allocation patterns can have different throughput characteristics than on .NET Framework with Workstation GC. The core cost of boxing—allocating a new object—remains the same. No matter the runtime, boxing adds memory and latency relative to no allocation.
Using ReadOnlySpan<T> and ref struct to Avoid Boxing
Span<T> is a ref struct; the compiler prevents it from being boxed or stored on the heap. Memory<T> is not a ref struct, but it lets you share the same data when you cannot use a ref struct. If your goal is specifically to avoid boxing, use Span<T> where the language rules allow it.
Span<int> buffer = stackalloc int[10];
// No boxing possible hereThis is an advanced technique, but it is useful in performance-critical code with value types.
Measuring Boxing Impact in Your Code
You cannot assume a performance problem without measurement. Use a profiler to identify allocations and CPU hotspots. The built-in .NET profilers or tools like BenchmarkDotNet can show you exactly where boxing occurs. To observe allocations, run your code with GC allocation tracking enabled. This gives concrete evidence rather than guesses.
If you see a large number of small objects being allocated in a loop, check for boxing. One useful technique is to inspect the JIT code—when you see a call to the box IL instruction, that is a boxing site.
Example: Optimizing a Request Handler
Consider a request handler that builds a response from integers:
public string BuildResponse(int userId, int status)
{
return $"User {userId} status {status}";
}On older .NET versions, this interpolation can box userId and status because it compiles to a string.Format call that accepts object. On newer .NET versions, interpolated string handlers may avoid the boxing, so measure before optimizing. If you do need to avoid boxing, one option is to call ToString() explicitly:
public string BuildResponse(int userId, int status)
{
return "User " + userId.ToString() + " status " + status.ToString();
}However, this still allocates additional strings. In a low-throughput scenario it is fine; in a high-throughput loop you might consider string.Create to build the string with fewer temporary allocations. The right tradeoff depends on the context.
Avoiding Boxing with Generic Restrictions
Adding a constraint such as where T : struct or where T : IEquatable<T> helps the compiler emit calls that avoid boxing, but the constraint alone does not remove the cost. The method must call through the generic type instead of converting T to object.
static bool AreEqual<T>(T a, T b) where T : IEquatable<T>
{
return a.Equals(b); // Calls IEquatable<T>.Equals, no boxing
}Without the constraint, a.Equals(b) boxes because the compiler can only call object.Equals.
The Hidden Cost in LINQ Queries
LINQ operations over non-generic collections can hide boxing cost. For example, adding an int to an ArrayList boxes it, and a later .Cast<int>() unboxes it. When working with large sequences, this can hurt performance. Using List<int> directly avoids the conversion because the source is already stored as int values.
Conclusion
Boxing is not a performance bug per se, but it becomes one when it appears in repetitive code paths. Understanding the distinction between boxing and unboxing—and knowing when the compiler inserts these operations—allows you to write efficient, predictable C# code. The key is to keep value types out of object-typed storage or in generic containers, and reserve boxing for cases where you truly need reference semantics. By doing so, you avoid unnecessary allocations and runtime checks, leading to cleaner and faster applications.
Try matching browser tools
All toolsSmall utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related C# guides
All C# guidesC# Dispose vs Destructor: Key Differences Explained
c# dispose vs destructor: Understand the difference between Dispose and destructors in C#, when each runs, and how to manage unmanaged resources correctly.
C# Variable Declaration: Syntax and Practical Usage
Learn how to declare variables in C# with explicit types, var, and nullable annotations, and understand how defaults, scope, and readability affect your choices.
C# Primary Constructors for Classes: Syntax and Usage
Learn how to use C# primary constructors for classes: syntax, initialization, dependency injection, and limitations with practical examples.
C# IComparer: Custom Sorting with IComparer<T>
Learn how to implement IComparer<T> in C# to define custom sort order for arrays and lists, handle nulls, and avoid common performance pitfalls.
More in C#
All C# guidesThe guides filed next to this one in C#, in library order.