الانتقال إلى المحتوى
.NETC#· 8 دقائق للقراءة

Stack vs Heap Is the Wrong Question: What Really Separates Value and Reference Types

Value types are about copying, not about the stack. Where your structs really live, and why it rarely matters.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A pull request turns the OrderLine class into a record struct because "structs live on the stack, so this takes load off the GC." A week later, support reports that coupon discounts stopped applying, though nobody touched the discount code. The culprit is a loop that reads var line = lines[i] and lowers line.Price. With a class, line pointed at the item in the list; with a struct, it's a copy, so the loop discounts copies and throws them away. And the lines never moved to the stack: they sit in the internal array of the List<OrderLine>, on the heap.

The common misconception

The belief goes like this: value types (int, DateTime, your structs) live on the stack, reference types (classes, arrays, strings) live on the heap, and that's what makes them different. It's in countless tutorials and interview answers, and Microsoft's own docs described value types that way for years.

It survives because it's half true. A local int in an ordinary method really does live in the method's stack frame, or in a CPU register, and vanishes when the method returns. Boxing is usually drawn as a value being copied from the stack to the heap, which reinforces the picture. And developers coming from C++ are used to choosing stack or heap themselves.

The trouble is that the rule turns one case of an implementation detail into a definition. It's wrong for fields, array elements, captured variables and async methods, and it hides what actually changes your program's behavior: copying.

What actually happens

The real difference: what a variable holds

A variable of a contains the instance itself. A variable of a reference type contains a reference to an instance stored elsewhere. Assignment, passing an argument and returning a result all copy what the variable holds. For a reference type that's the reference, so two variables can point at one object and see each other's changes. For a value type it's the whole value, so every variable has its own independent copy.

That's the contract the language guarantees, and the part you observe in code. One detail catches people out: copying a struct copies its fields, and a reference-type field is copied as a reference. If your struct holds a List<string>, both copies share that list.

Storage follows the variable, not the type

Where a value is stored depends on where its variable lives and how long that variable must survive. Here is one small struct in five places:

C# Route.cs
public readonly record struct Point(int X, int Y);public class Route{    public Point Start { get; set; }                // part of every Route object's memory    public Point[] Stops { get; } = new Point[16];  // 16 Points stored inline in one heap array    public int Demo()    {        var a = new Point(1, 2);       // ordinary local: stack frame or CPU registers        object boxed = a;              // boxing: copies a into a new object, normally on the heap        var b = new Point(3, 4);       // captured by the lambda below: b lives in a closure object        Func<int> shiftX = () => b.X + 1;        return a.X + shiftX() + Start.X + Stops.Length + boxed.GetHashCode();    }    public async Task<int> LaterAsync(Task signal)    {        var c = new Point(5, 6);       // still needed after the await, so it becomes a field        await signal;                  // of the async state machine, which is copied to the        return c.X;                    // heap if the method really has to wait    }}

Walk through it:

  • Fields: Start isn't on any stack. Its 8 bytes are part of the Route object, which normally lives on the heap.
  • Array elements: an array of structs stores the values themselves, side by side, inside the array object. List<T> keeps its items in an array, so the OrderLine data stayed on the heap.
  • Captured locals: the compiler turns b into a field of a hidden class, and in .NET 10 that closure object is still allocated on the heap.
  • Async methods: locals that must survive an await become fields of a compiler-generated state machine. In Release builds it stays on the stack if every awaited task has already finished, and is copied to the heap if the method has to wait.
  • Boxing: converting a value to object or to an interface copies it into a new object. Changing a later doesn't change boxed.

Only a matches the folklore, and even a may never touch memory: with an optimization called physical promotion, the JIT can keep a struct's fields in CPU registers.

Reference types don't always live on the heap either

The mirror-image rule is breaking down too. The JIT uses to find objects that can't outlive the method that creates them, and can allocate those on the stack: boxes since .NET 9, plus small fixed-size arrays and delegates in .NET 10. None of this changes what your code means, only where the bytes go, which is exactly why "stack or heap?" is the wrong question to design around.

The bug that really matters: copies

Back to the coupon bug, before and after the fix:

C# Program.cs
var lines = new List<OrderLine> { new("SKU-1", 100m), new("SKU-2", 40m) };for (var i = 0; i < lines.Count; i++){    var line = lines[i];      // a copy of the struct, not the item inside the list    line.Price -= 10m;        // discounts the copy}Console.WriteLine(lines[0].Price); // 100: the discount was silently lostpublic record struct OrderLine(string Sku, decimal Price);

The only change to the type is readonly. The loop stops fighting the copy: it builds a new value with with and stores it back in the list. And if OrderLine is something you want to update in place and share, it was a reference type all along, and going back to a class is a perfectly good fix.

Myth vs reality

MythReality
Value types live on the stackA value lives where its variable lives: stack frame, register, object, array, closure or async state machine
Reference types always live on the heapThe JIT can stack-allocate objects that never escape, such as boxes, small arrays and delegates
A struct means no heap allocationsStructs in a List<T> live in its heap array, and each boxing creates a new object
Copying a struct copies everything inside itReference-type fields are copied as references, so both copies share those objects
The difference is the memory locationThe difference is semantics: copying the value versus copying a reference

How to apply it in your project

  1. Choose by meaning firstIs the type a value, like an amount, a coordinate or a date range, or a thing with an identity that changes over time, like an order? Things with identity should be classes.
  2. Keep structs small and immutableMicrosoft's design guidelines suggest a struct only for a single, immutable value under 16 bytes that won't be boxed often. Mark it readonly so the compiler enforces the immutability.
  3. Hunt for lost copiesLook for code that reads a struct from a list, dictionary or array, changes it, and never writes it back. In hot paths, also look for structs passed as object or as an interface: each one is a box.
  4. Measure before you claim a winProve performance changes with a benchmark that reports allocations, such as BenchmarkDotNet's [MemoryDiagnoser]. The JIT may already remove the allocation you want to save, or your change may add boxes elsewhere.

Key takeaways

  • Value versus reference is about what a variable holds and what gets copied, not where memory is allocated.
  • A struct lives wherever its variable lives, which often means inside a heap object, array, closure or state machine.
  • The JIT is free to move things: in .NET 10 it can stack-allocate some non-escaping objects and keep struct fields in registers.
  • Most struct bugs are lost updates on copies; readonly structs turn them into compile errors.
  • Pick struct or class by semantics, and claim a performance win only after measuring it.

📚 المصادر

  1. Value types (C# reference) — Microsoft Learn
  2. Boxing and Unboxing (C# programming guide) — Microsoft Learn
  3. Choosing Between Class and Struct (Framework Design Guidelines) — Microsoft Learn
  4. What's new in .NET 10 runtime: stack allocation and escape analysis — Microsoft Learn
  5. The Stack Is An Implementation Detail, Part One — Eric Lippert (Microsoft Learn archive)

التعليقات (0)