skip to content

In C#, is it true that value types live on the stack, and where does a struct field or a struct array element actually live?

level: middleimportance: should knowfreq 60%

answer

  1. storage follows the variable
  2. fields are inline in their container
  3. arrays of structs are one object
  4. captured locals move into objects

basics

~20 s

Only as a simplification. A value lives wherever its variable lives: a struct local usually sits on the stack or in registers, but a struct field of a class or a struct array element is stored inline inside that heap object.

solid answer

~40 s

C# defines value types by **copy semantics**, not by location. Where a value is stored follows the variable that holds it: a local or parameter usually lives on the stack or in a register; a struct field of a class lives **inline inside the object** on the managed heap; a `Point[]` is **one array object** with every `Point` stored inline; a field of a struct lives wherever that struct lives. A local captured by a lambda becomes a field of a compiler-generated closure object, so it normally ends up on the heap too. The reverse simplification also leaks: since .NET 9 and .NET 10 the JIT can stack-allocate some objects that never escape a method. So the real distinction is "copied on assignment" vs "shared through a reference".

code

csharp · 29 lines
csharp
const int N = 1_000;

long before = GC.GetAllocatedBytesForCurrentThread();
var points = new Point[N];                  // one array object; each Point stored inline
for (int i = 0; i < N; i++) points[i] = new Point(i, i);
long pointBytes = GC.GetAllocatedBytesForCurrentThread() - before;

before = GC.GetAllocatedBytesForCurrentThread();
var products = new Product[N];              // one array of references...
for (int i = 0; i < N; i++) products[i] = new Product(i);   // ...plus N heap objects
long productBytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine($"Point[{N}] filled:   {pointBytes} bytes allocated");
Console.WriteLine($"Product[{N}] filled: {productBytes} bytes allocated");
GC.KeepAlive(points);
GC.KeepAlive(products);

struct Point
{
    public int X;
    public int Y;
    public Point(int x, int y) { X = x; Y = y; }
}

class Product
{
    public int Id;
    public Product(int id) { Id = id; }
}

go deeper

for a junior

Recall that the stack-and-heap slogan is a simplification and that a struct inside a class or an array lives inside that object.

for a middle

Explain the rule that storage follows the variable, with the class-field, array-element and captured-local cases.

for a senior

Reason about allocation counts from layout, such as one array of inline structs versus an array plus one object per element, and verify with allocation measurements.

for a principal

Steer teams away from choosing struct or class by imagined location and toward copy semantics, size and measured allocation profiles.

## Where the slogan comes from "Value types live on the stack, reference types live on the heap" is the most repeated C# simplification. It is accurate for one case: a **local variable or parameter** of a struct type, which the runtime usually keeps in the method's stack frame or in a register. It breaks for every other place a value can be stored, and C# itself does not define value types by location at all. Microsoft's C# fundamentals describe a struct as holding its data directly in the instance, and a class variable as holding a reference to an object on the managed heap; the struct definition says nothing about a stack. The language defines them by **what a variable holds**: a value-type variable contains the instance, a reference-type variable contains a reference to an object. The rule that replaces the slogan is short: **a value lives wherever the variable that holds it lives.** ## Struct storage, case by case | Where the struct is declared | Where its bytes live | |---|---| | local variable or parameter | the method's stack frame or a register | | field of a class instance | inline inside that object, normally on the managed heap | | element of an array | inline inside the array object | | field of another struct | wherever the outer struct lives | | local captured by a lambda or local function | a field of a compiler-generated closure object | | converted to `object` or an interface | a separate box object (see the lesson on boxing) | Two rows matter most on an inventory screen: - **A struct field of a class.** A `Product` class with a `Point Location` field holds the eight bytes of `X` and `Y` *inside* the `Product` object. There is no separate `Point` object and no reference to one. - **An array of structs.** `new Point[1000]` allocates **one** object whose payload is 1,000 consecutive `Point` values. A `Product[1000]` allocates one array of 1,000 references, and each `new Product(...)` is another heap object. Measured with `GC.GetAllocatedBytesForCurrentThread` on 64-bit .NET 10, filling a `Point[1000]` allocated 8,024 bytes in all, while filling a `Product[1000]` allocated 32,024 bytes: the same 8,024-byte array of references plus 24 bytes for each `Product` object. ## Locals that move off the stack Even a struct **local** does not always stay in a stack frame: 1. If a lambda or local function captures it, the compiler turns the local into a field of a generated closure class. The method and the lambda then share that one field, which is why a lambda that adds 10 to `origin.X` changes what the method reads afterwards. 2. Locals of `async` methods and iterators that live across an `await` or a `yield` are hoisted into a compiler-generated state machine, which can end up on the heap; the details belong to the material on the async state machine. 3. A `ref struct` such as `Span<T>` is the opposite case: the compiler forbids it from ever reaching the heap, which is covered with ref structs. ## Objects that move onto the stack The slogan's other half is also a simplification. The JIT performs **escape analysis**: an object that provably does not outlive its method can be allocated on the stack. .NET 9 added this for some boxes, and .NET 10 extended it to small fixed-size arrays and to some delegates. This is an optimisation the runtime is free to apply or not; it never changes what your code observes, because a reference type still behaves as a shared reference. ## Why the distinction matters in practice - **Choosing struct vs class by location is the wrong reasoning.** Choose by semantics: should assignment produce an independent copy or a second reference to one thing? - **Allocation counts do differ.** A list of 1,000 small structs costs one backing array; a list of 1,000 class instances costs 1,001 objects for the collector to trace. That trade-off, and the copying cost of large structs, is covered with value-type trade-offs. - **A struct field is not a hidden heap object**, so copying the containing class's reference never copies the struct, while copying a struct copies every byte. An interviewer who asks this wants the candidate to drop the slogan, state the "storage follows the variable" rule, and give the class-field and array examples without prompting.

  • Does replacing a `List<Product>` class with a `List<ProductInfo>` struct reduce allocations for 1,000 items?
    Yes: the list's backing array holds the 1,000 structs inline, so there is one array instead of an array plus 1,000 objects. The cost moves to copying: every read through the indexer copies the whole struct, so it pays off only for small, value-like types.
  • A `Product` class has a `Point Location` field. Does copying a `Product` reference copy the `Point`?
    No. Copying the reference gives a second name for the same `Product` object, and the `Point` bytes stay inside that one object. Only copying the `Point` itself, for example `var p = product.Location;`, produces an independent copy.

  • Value types always live on the stack.
  • Reference types are always allocated on the heap, without exception.
  • A struct field inside a class is allocated separately on the stack.
  • An array of structs holds references to separately allocated structs.
  • Struct vs class is mainly a choice between stack and heap.

Assumes .NET 10; JIT stack allocation of non-escaping boxes arrived in .NET 9 and of small arrays and delegates in .NET 10, while the struct storage rules hold in every release.