Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 182 ยท Memory and Performance

Boxing, Unboxing and Value Semantics

Learn what boxing and unboxing do in C#, how to count the allocations they cause, how generics avoid them, and how struct copying, readonly struct and in parameters work.

Value types such as int, double, bool and your own structs normally live inline: in a local variable, inside an array, inside another object. Reference types live on the heap and are reached through a reference. Most of the time you never think about the difference. But sometimes C# has to treat a value as an object, and then it performs a hidden conversion called boxing: it allocates a small object on the heap and copies the value into it.

Boxing is easy to trigger by accident and, in a hot loop, it quietly produces millions of short-lived objects for the garbage collector. This lesson shows exactly when boxing happens, how to prove it by counting allocated bytes, how to avoid it with generics, and then looks at the other half of value semantics: how structs are copied, why readonly struct and in parameters exist, and how big a struct really is. If value and reference types are still fuzzy, start with value and reference types and structs.

What boxing does

Assigning a value type to object (or to an interface it implements) boxes it. Casting back is unboxing: the runtime checks the box holds exactly that type and copies the value out.

C# Boxing and unboxing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The box is an independent copy. Changing number afterward leaves boxed at 42. Unboxing needs the exact type: (long)boxed would throw InvalidCastException, even though an int converts to long normally.

C# Unboxing to the wrong type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

This throws System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int64'. The fix is (long)(int)boxed, or Convert.ToInt64(boxed).

Where boxing hides

You will rarely write object o = 5;. It sneaks in through:

  • Passing a value type to a parameter of type object or params object[] (the classic string.Format("{0}", 5) and older logging APIs).
  • Using non-generic collections such as ArrayList and Hashtable.
  • Calling a method of object that the struct did not override (for instance GetType()), or calling ToString() / Equals / GetHashCode on a struct that does not override them.
  • Converting a struct to an interface it implements (IComparable c = myStruct;).
  • Older string APIs such as string.Format("{0}", 5) or Console.WriteLine("{0}", 5) with several arguments (they take object). Interpolated strings ($"{x}") avoid this in modern C#.

Counting the cost

You can see the allocation without a profiler: measure the bytes allocated by the current thread (GC.GetAllocatedBytesForCurrentThread) around a loop. Because the measurement is made in bytes, it does not depend on machine speed.

C# ArrayList versus List of int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each boxed int costs 24 bytes on a 64-bit runtime: 8 bytes object header, 8 bytes method table pointer, 4 bytes value, padded to 24. A thousand boxes is roughly 24 KB, versus a single 4,000-byte array for List<int> with a preset capacity (plus the list object). List<int> also reads faster, because the numbers sit next to each other in memory instead of being scattered across the heap.

Avoiding boxing with generics

Generics were designed in .NET 2.0 to solve exactly this. For value-type arguments, the runtime compiles a specialised copy (List<int>, Dictionary<int, string>), so values stay unboxed. Two rules help you keep it that way:

  1. Use generic collections (lists, dictionaries) instead of ArrayList/Hashtable.
  2. Write your own APIs as generic methods rather than taking object, and use constraints when you need to call members (see generic constraints).

An interface call on a value type normally boxes. A constrained generic call does not:

C# Interface parameter versus generic constraint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both methods compile to the same logic, yet only the interface version allocates. This is also why modern .NET uses generic interfaces such as IEquatable<T> and IComparable<T>: Dictionary<TKey, TValue> can compare your struct keys without boxing, as long as the struct implements IEquatable<T> (see object methods).

If you write a struct that will be used as a dictionary key or compared often, override Equals(object) and GetHashCode, and also implement IEquatable<T>. Without it, the default comparison uses reflection-like logic and boxes. Making the struct a record struct generates all of this for you (records).

Copy semantics: structs are copied

The other half of value semantics is copying. Assigning a struct, passing it to a method or returning it gives the receiver an independent copy of all fields. That is what makes small structs safe to share, and also what makes big structs slow to pass around.

C# A struct is copied on assignment and on calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Mutable structs lead to subtle bugs, because it is easy to mutate a copy. The classic trap is a struct stored in a collection or exposed through a property:

C# Mutating a copy of a struct in a list (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler stops you with error CS1612: Cannot modify the return value of 'List<Point>.this[int]' because it is not a variable, since the indexer returns a copy. Changing it would silently do nothing. Prefer immutable structs, and replace the whole element (points[0] = points[0] with { X = 5 }; on a record struct).

readonly struct, in and ref readonly

When a struct is large, copying it for every call costs time. Passing by reference avoids the copy. For that to be safe, C# offers three tools:

  • readonly struct: all fields are read-only, so no one can mutate it. The compiler knows a call on a readonly struct never changes it and avoids making "defensive copies".
  • in parameter: passes the argument by reference but the method cannot assign to it. Callers can pass a plain variable or write in x.
  • ref readonly (C# 12 for parameters, C# 7.2 for returns): the explicit form for parameters and returns that give read-only access without copying.
C# A readonly struct passed with in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Callers may leave out in for an in parameter (the compiler passes a reference anyway), but for ref readonly parameters the compiler warns (CS9192) unless you write in or ref at the call site. in is a hint plus a promise. If the struct is not readonly, calling a member through an in parameter makes the compiler copy it first (a "defensive copy"), which defeats the purpose. So: use in only with readonly struct types, and only for structs bigger than about 16 bytes. For small structs (a point, a pair of ints), passing by value is just as fast and simpler.

How big is a struct?

Use Unsafe.SizeOf<T>() from System.Runtime.CompilerServices to see how large a struct is in memory. It includes padding the runtime adds to align fields.

C# Measuring struct sizes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Padded and Packed hold the same three fields, yet Padded is 24 bytes and Packed is 16. Structs use sequential layout by default, and the 8-byte long must start on an 8-byte boundary, so the runtime inserts padding after a lone byte that precedes it. Putting the big field first and the small ones together saves space. A reference (any class instance, string) is 8 bytes on a 64-bit process.

A common guideline from the .NET design docs is to make a type a struct only if it is small (about 16 bytes or less), short-lived or embedded, logically a single value, and immutable. Otherwise a class is usually better.

Choosing: when to care

Boxing and copying only matter at scale. Concrete advice:

Situation Do this
Storing numbers in collections Use List<int>, never ArrayList
API that accepts any value Make it generic (void Log<T>(T value)) instead of object
Calling interface members on a struct in a generic method Add a constraint (where T : IMeasure)
Struct as dictionary key Implement IEquatable<T> (or use record struct)
Large struct passed to a hot method readonly struct plus in
Small data, hot loop Plain small immutable struct, passed by value
Anything in ordinary business code Write clearly first; measure before optimizing

Look for boxing in a profiler's allocation view or with analyzers (CA1859 and related rules suggest more specific types). Never guess; count allocated bytes as shown above and see measuring performance.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you assign an int to an object variable?

    Boxing wraps the value in a new heap object. Changing the original variable later does not change the box, because the value was copied.
  2. 2. Why does (long)boxedInt throw InvalidCastException when boxedInt holds an int?

    Unboxing checks the box's exact type. Use (long)(int)boxedInt or Convert.ToInt64 to convert.
  3. 3. Which change removes the boxing from a method void Show(object value) called with ints?

    A generic method is compiled for the value type itself, so the int is never converted to object. Nullable annotations and GC.Collect do not change that.
  4. 4. Which code mutates only a copy of the struct?

    Assigning a struct to a new variable copies it, so p.X = 5 changes the copy. A ref local and array element access modify the original storage, and the assignment replaces the element.
  5. 5. When is an in parameter a good idea?

    in passes by reference without allowing writes. It pays off only for big structs, ideally readonly ones; otherwise the compiler may make defensive copies.

Summary

  • Boxing copies a value type into a new heap object when it is used as object or as an interface; unboxing needs the exact type and copies it back out.
  • Hidden boxing comes from object parameters, non-generic collections, interface conversions and structs that do not override Equals/GetHashCode.
  • Generics and generic constraints keep value types unboxed; IEquatable<T> keeps struct keys fast.
  • Structs are copied on assignment, argument passing and return. Mutating a copy is a classic bug (CS1612), so prefer immutable structs.
  • readonly struct, in and ref readonly avoid copying big structs safely. For tiny structs, pass by value.
  • Unsafe.SizeOf<T>() shows real struct sizes including padding. Measure allocations in bytes before and after changes.

Next: Measuring and Improving Performance