Classes vs structs: where do allocations actually happen?
"Structs live on the stack, classes live on the heap" is the most repeated half-truth in .NET. Let's replace it with a model that actually predicts what the GC will see.
1. The real rule: reference types vs value types
The difference between a class and a struct is not where it lives. It's how it's stored and passed:
- A class instance is an object on the managed heap. Variables hold a reference (a pointer) to it. Assigning the variable copies the reference, not the object.
- A struct value is stored inline — directly inside whatever contains it. Assigning it copies the whole value.
So a struct lives wherever its container lives. A local struct lives in the method's stack frame (or in registers). A struct field inside a class lives on the heap, inside that object. A struct[] stores all values contiguously inside the array object — on the heap.
public sealed class PointClass { public int X, Y; }
public struct PointStruct { public int X, Y; }
void Demo()
{
var a = new PointClass(); // heap allocation (24 bytes on x64)
var b = new PointStruct(); // no heap allocation: 8 bytes in the stack frame
var a2 = a; // copies a reference — a2 and a point to the same object
var b2 = b; // copies 8 bytes — b2 is an independent value
}
class — reference semantics
struct — value semantics
2. What a heap object costs
On 64-bit .NET every heap object carries two hidden pointer-sized fields: the object header (sync block index / hash code / lock info) and the MethodTable pointer (type identity, vtable). That's 16 bytes of overhead, and the minimum object size is 24 bytes.
| Type | Payload | Size on heap (x64) |
|---|---|---|
class with one int | 4 B | 24 B |
class with two int | 8 B | 24 B |
class with two long | 16 B | 32 B |
struct with two int (as a local) | 8 B | 0 B — not on the heap |
PointStruct[1000] | 8 000 B | ~8 024 B, 1 allocation |
PointClass[1000] filled | 8 000 B | ~8 024 B array + 1000 × 24 B = ~32 KB, 1001 allocations |
The last two rows are the important ones. The class version is four times larger, scatters objects across memory (worse cache locality), and gives the GC 1000 extra objects to trace.
3. Hidden allocations with structs: boxing
Structs avoid the heap only as long as you treat them as values. The moment a struct is converted to object, a non-generic interface, or ValueType, the runtime boxes it — allocates a heap object and copies the value into it.
public struct Money : IComparable<Money>
{
public decimal Amount;
public int CompareTo(Money other) => Amount.CompareTo(other.Amount);
}
Money m = new() { Amount = 10 };
object o = m; // box: allocation
IComparable<Money> c = m; // box: allocation (interface-typed variable)
var list = new ArrayList { m }; // box: non-generic collection
Console.WriteLine("{0}", m); // box: params object[]
// No boxing: generic constraint lets the JIT specialize for the struct
static int Compare<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b);
Compare(m, m); // zero allocations
Typical boxing traps to look for in a profiler:
- Storing structs in
object,ArrayList,Hashtable, or non-generic interfaces. - Calling
Equals(object)/GetHashCode()on a struct that doesn't override them — the defaultValueType.Equalscan box and uses reflection. ImplementIEquatable<T>, or use arecord struct, which generates it for you. - Using a struct as a
Dictionarykey withoutIEquatable<T>. - String formatting via
params object[]APIs. Interpolated strings ($"...") use interpolation handlers and avoid boxing.
4. Hidden costs with structs: copies
Structs don't allocate, but they copy. Every pass by value, every return, every assignment copies the full struct. For a 16-byte struct that's trivially cheap. For a 128-byte struct passed through a hot loop, it isn't.
public readonly struct Matrix4x4Data // 64 bytes
{
public readonly float M11, M12, M13, M14, M21, M22, M23, M24,
M31, M32, M33, M34, M41, M42, M43, M44;
}
// Copies 64 bytes per call
static float TraceByValue(Matrix4x4Data m) => m.M11 + m.M22 + m.M33 + m.M44;
// Passes a reference to the caller's value — no copy, read-only
static float TraceByRef(in Matrix4x4Data m) => m.M11 + m.M22 + m.M33 + m.M44;
Defensive copies. When you call a method on a struct through an in parameter or a readonly field, the compiler must guarantee the value isn't mutated. If the struct isn't readonly, it silently makes a copy before every call. Mark structs readonly struct (or individual members readonly) so the compiler can skip those copies.
A practical guideline: keep structs small (roughly ≤ 16–24 bytes), immutable, and logically a single value — like DateTime, Guid, Vector3, or a money amount. For bigger data, pass by in / ref readonly, or use a class.
5. Mutable structs bite
Value semantics means you're often modifying a copy without noticing:
public struct Counter { public int Value; public void Inc() => Value++; }
var list = new List<Counter> { new() };
// list[0].Value++; // CS1612: cannot modify the return value — it's a copy
var tmp = list[0]; tmp.Inc(); // increments the copy; list[0].Value is still 0
// Arrays return the element by reference, so this works:
var arr = new Counter[1];
arr[0].Inc(); // arr[0].Value == 1
// For List<T>, get a ref with CollectionsMarshal:
ref var c = ref CollectionsMarshal.AsSpan(list)[0];
c.Inc(); // list[0].Value == 1
6. Stack-only types: ref struct and Span<T>
A ref struct is a struct the compiler guarantees will never end up on the heap: it can't be boxed, can't be a field of a class, and can't be captured by a lambda. That's what makes Span<T> safe — it can point at stack memory.
static int SumDigits(ReadOnlySpan<char> input)
{
int sum = 0;
foreach (var ch in input)
if (char.IsAsciiDigit(ch)) sum += ch - '0';
return sum;
}
// Small temporary buffer on the stack instead of new byte[256]
Span<byte> buffer = stackalloc byte[256];
int written = Encoding.UTF8.GetBytes("hello", buffer);
// Slicing a string without allocating substrings
int s = SumDigits("order-2026-11".AsSpan(6));
Since C# 13, ref struct types can implement interfaces and be used as generic arguments via the allows ref struct anti-constraint — still without ever being boxed.
7. .NET 10: the JIT can remove class allocations too
The line between "class = heap" and "struct = stack" got blurrier in recent releases. The JIT performs escape analysis: if it can prove an object never escapes the method (not stored in a field, not returned, not passed somewhere it might be kept), it can allocate it on the stack and skip the GC entirely. .NET 9 used this to eliminate some boxes; .NET 10 extends it to more cases, including small fixed-size arrays and some delegates/lambdas that don't escape.
static int Distance()
{
// Never escapes this method — a candidate for stack allocation in .NET 10
var p = new PointClass { X = 3, Y = 4 };
return p.X * p.X + p.Y * p.Y;
}
Don't design around it. Escape analysis is an optimization, not a guarantee: it depends on inlining, object size, and the JIT tier, and the code above may still allocate in Tier-0 code before tiering kicks in. Write the clearest code, then measure.
8. Measure, don't guess
BenchmarkDotNet's [MemoryDiagnoser] shows allocated bytes per operation and GC counts. That one column settles most class-vs-struct arguments.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<PointBenchmarks>();
[MemoryDiagnoser]
public class PointBenchmarks
{
private const int N = 1_000;
[Benchmark(Baseline = true)]
public long Classes()
{
var arr = new PointClass[N];
for (int i = 0; i < N; i++) arr[i] = new() { X = i, Y = i };
long sum = 0;
foreach (var p in arr) sum += p.X + p.Y;
return sum;
}
[Benchmark]
public long Structs()
{
var arr = new PointStruct[N];
for (int i = 0; i < N; i++) arr[i] = new() { X = i, Y = i };
long sum = 0;
foreach (var p in arr) sum += p.X + p.Y;
return sum;
}
}
Expect the Allocated column to show roughly 32 KB for Classes versus roughly 8 KB for Structs — the numbers from the table in section 2 — with the struct version also faster thanks to contiguous memory. Run it on your own machine; exact timings vary by hardware.
For real applications, use dotnet-counters (watch gc-heap-size and allocation rate), dotnet-trace with the GC allocation events, or the allocation views in Visual Studio / Rider.
9. Cheat sheet
| Choose a… | When |
|---|---|
readonly struct / record struct | Small (≤ ~16–24 B), immutable, value-like data; lots of instances in arrays; hot paths where allocation rate matters. |
class / record | Identity matters; large or mutable shared state; polymorphism via inheritance; long-lived objects; anything you'd otherwise box constantly. |
ref struct / Span<T> | Short-lived views over memory, parsers, formatters, temporary buffers with stackalloc. |
- Structs are stored inline; they're on the stack only when their container is.
- Boxing turns a struct into a heap allocation — use generics with constraints and
IEquatable<T>. - Big structs trade allocations for copies — use
in,ref readonly, andreadonly struct. - .NET 10's escape analysis can stack-allocate some non-escaping objects, but it's a bonus, not a contract.
- Always confirm with
[MemoryDiagnoser].