The CLR: Stack, Heap and Handles

The CLR: Stack, Heap and Handles in C#: Imagine you work at a desk in front of an enormous warehouse.

The Analogy: The Desk and the Warehouse

Imagine you work at a desk in front of an enormous warehouse. Small things you are using right now — a note with a phone number, a page count, a yes-or-no answer — you keep on the desk itself. The desk is fast: everything on it is within arm's reach, and when you finish a task you sweep the whole surface clear in one motion. But the desk is small, and it has a strict discipline: the last thing you put down is the first thing you pick up, and nothing you leave on it survives past the end of the task.

Anything large or long-lived goes into the warehouse. You do not carry the crate to your desk; you write down its shelf number on a note and keep the note on the desk instead. The note is small and cheap to copy, the crate never moves, and two notes can point at the same crate — so if you rearrange the crate's contents, everyone holding a note sees the change. Clearing your desk does not empty the warehouse, which is why the warehouse needs its own cleanup crew.

This is exactly the CLR's split. The stack is the desk: one per thread, roughly a megabyte, strictly last-in-first-out, swept clean when a method returns. The heap is the warehouse: shared across the whole process, effectively as large as memory allows, and tidied by the garbage collector. A struct is a thing you keep on the desk; a class instance is a crate in the warehouse, and the variable holding it is the note with the shelf number.

Almost every surprising behaviour in C# — why modifying a struct inside a method changes nothing, why two variables can see each other's edits, why a "small" object still costs twenty-four bytes, why boxing is slow — falls out of that one distinction. This lesson is about seeing the desk and the warehouse behind the code you already write.


Syntax or Core Structure

using System;

struct Point { public int X; public int Y; }   // lives where it is declared

class Box { public int Value; }                // always on the heap

class Program
{
    static void Mutate(Point p, Box b)
    {
        p.X = 99;          // edits a copy - invisible to the caller
        b.Value = 99;      // follows the note to the crate - visible everywhere
    }

    static void MutateRef(ref Point p) => p.X = 42;   // edits the caller's storage

    static void Main()
    {
        Point point = new Point { X = 1, Y = 2 };
        Box box = new Box { Value = 1 };

        Mutate(point, box);
        Console.WriteLine("point.X = " + point.X + ", box.Value = " + box.Value);

        MutateRef(ref point);
        Console.WriteLine("after ref, point.X = " + point.X);

        object boxed = point;      // boxing: a copy is placed on the heap
        point.X = 7;
        Console.WriteLine("boxed.X = " + ((Point)boxed).X + ", point.X = " + point.X);

        Box other = box;           // copies the note, not the crate
        other.Value = 5;
        Console.WriteLine("box.Value = " + box.Value
            + ", same object = " + ReferenceEquals(box, other));
    }
}

Output:

point.X = 1, box.Value = 99
after ref, point.X = 42
boxed.X = 42, point.X = 7
box.Value = 5, same object = True

Four lines, four different lessons. Passing point copies eight bytes onto the callee's desk, so p.X = 99 writes to storage that vanishes when Mutate returns. Passing box copies a note, and both notes name the same crate, so b.Value = 99 is visible to the caller. ref closes the gap by handing over the address of the caller's storage rather than a copy of its contents.

Boxing is the line people misread. object boxed = point; does not make boxed an alias for point — it allocates a new heap object, copies the eight bytes into it, and stores a note. That is why changing point.X to 7 afterwards leaves boxed holding 42. Every boxing operation is an allocation, and unboxing is a copy back out, which is why boxing in a hot loop shows up so clearly in a profiler.

ReferenceEquals(box, other) returning True states the reference-type rule plainly: assignment copies the reference. There is exactly one Box in this program, and two variables that both know where it is.


Technical Depth: What the Runtime Really Stores

Value type (struct, int, enum)Reference type (class, array, string)
StorageInline: on the stack, or inside its containing objectAlways on the heap
AssignmentCopies the whole valueCopies the reference
DefaultAll fields zeroednull
EqualityField-by-field (memberwise) unless overriddenReference identity unless overridden
OverheadNone16 bytes of header on 64-bit
Passed to a methodCopied, unless ref/in/outReference copied

The 24-byte minimum

Every heap object carries two hidden words: a sync block index (used by lock, hash codes, and COM interop) and a method table pointer (the type identity that makes virtual dispatch and casting work). On 64-bit that is 16 bytes before any of your fields, and the allocator rounds up to a multiple of 8 with a 24-byte floor. A class Point { int X; int Y; } therefore costs 24 bytes plus 8 for the reference, against 8 bytes for the equivalent struct — a 4x difference that only matters when you have millions of them, which is exactly when it matters a great deal.

Where a struct actually lives

"Structs live on the stack" is a useful lie. A struct lives wherever it is declared: a local goes on the stack, a field of a class goes inside that class's heap allocation, an element of Point[] goes inline in the array's heap block. The last case is the one you exploit for performance — a million Point values in an array are a million contiguous 8-byte pairs the CPU can stream through, while a million Box references are a million pointer-chases to scattered addresses.

The ref family

void Read(in Point p)            { /* p is readonly - no copy, no writes */ }
void Write(ref Point p)          { p.X = 1; }        // caller's storage
void Create(out Point p)         { p = default; }    // must assign before returning
ref int Slot(int[] data)         => ref data[0];     // returns a location
readonly struct Money { }                            // whole struct is immutable
ref struct Cursor { }                                // stack-only: cannot be boxed

in is the one worth knowing about: it avoids copying a large struct, but on a non-readonly struct the compiler must insert a defensive copy before every method call, which can make in slower than passing by value. Mark large structs readonly struct and the copies disappear.

Stack allocation and stack-only types

stackalloc carves a buffer straight out of the current frame — no allocation, no garbage, and no way to outlive the method:

Span<byte> buffer = stackalloc byte[256];    // freed when the method returns

That safety is enforced by ref struct. Span<T> is one, which is why you cannot put a Span in a field of a class, capture it in a lambda, box it, or use it across an await — any of those would let a note outlive the desk it points at. Keep stackalloc sizes small and constant; a size taken from user input is a stack overflow waiting to happen.

Handles: telling the collector what to keep

A note on your desk keeps a crate alive. When something outside the managed world needs to hold or release a crate, you use a handle:

HandleEffect
GCHandle.Alloc(obj)Normal: keeps the object alive until freed
GCHandleType.WeakDoes not keep it alive; Target becomes null after collection
GCHandleType.Pinned / fixedObject may not be moved, so native code can hold its address
WeakReference<T>The friendly wrapper for caches that must not cause leaks

Pinning is the dangerous one: the collector compacts the heap by sliding objects together, and a pinned object is a rock in the stream. Pin briefly, pin rarely, and always free the handle in a finally.

Compilation, not interpretation

C# compiles to IL, and the JIT turns IL into machine code the first time each method runs. Tiered compilation compiles quickly at first and recompiles hot methods with full optimisation, which is why a benchmark's first thousand iterations are meaningless. ReadyToRun and Native AOT shift that work to build time, trading startup speed for larger binaries and, in AOT's case, no runtime code generation at all.


Real World Example: The Struct That Would Not Update

A page-hit tracker uses a mutable struct to keep the counters allocation-free. The counts stay stubbornly at zero, and the code looks correct — this is the single most common way the desk-and-warehouse distinction bites in real projects.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;

struct Counter
{
    public string Name;
    public int Hits;
    public void Hit() => Hits++;
}

class Program
{
    static void Main()
    {
        List<Counter> list = new List<Counter>
        {
            new Counter { Name = "home",  Hits = 0 },
            new Counter { Name = "about", Hits = 0 }
        };

        // 1. The iteration variable is a copy of the element.
        foreach (Counter c in list) c.Hit();
        Console.WriteLine("after foreach:   " + list[0].Hits);

        // 2. Read out, mutate, write back - the write-back is mandatory.
        for (int i = 0; i < list.Count; i++)
        {
            Counter copy = list[i];
            copy.Hit();
            list[i] = copy;
        }
        Console.WriteLine("after copy-back: " + list[0].Hits);

        // 3. An array element IS the storage, so no copy is involved.
        Counter[] array = list.ToArray();
        array[0].Hit();
        Console.WriteLine("array element:   " + array[0].Hits);

        // 4. A span's indexer returns a reference into the backing store.
        Span<Counter> span = CollectionsMarshal.AsSpan(list);
        span[0].Hit();
        Console.WriteLine("through span:    " + list[0].Hits);
    }
}

Output:

after foreach:   0
after copy-back: 1
array element:   2
through span:    2

Step 1 is the bug, and it is silent. foreach over a List<Counter> hands you a copy of each element; c.Hit() faithfully increments that copy, and the copy is discarded at the end of the iteration. No warning, no exception, no effect. Worse, the equivalent line list[0].Hit() also compiles — the indexer returns a copy, the method mutates the temporary, and the result is thrown away. Only list[0].Hits = 1 is rejected outright, because assigning to a field of a returned value is a compile error rather than a silent no-op.

Step 2 is the correct workaround for a List<T>: read the element into a local you own, mutate that, and assign it back through the indexer's setter. Verbose, but explicit about the copy — and the moment someone deletes the list[i] = copy; line, the counter silently stops working again, which tells you how fragile the design is.

Steps 3 and 4 show the two places where element access gives you the storage rather than a copy. An array indexer produces a managed reference to the element itself, so array[0].Hit() genuinely mutates the array. CollectionsMarshal.AsSpan exposes a List<T>'s backing array as a Span<T>, whose indexer returns ref T — so span[0].Hit() reaches through to the list's own storage, which is why the final line prints 2 rather than 1. That span is only valid until the list resizes; adding an item can allocate a new backing array and leave the span pointing at the old one.

The real lesson is not the workaround but the design: make structs readonly and treat them as values, or use a class when the thing has identity and changes over time. Every one of these problems disappears if Counter is a readonly record struct with a Hit() that returns a new value, or a plain class whose crate everybody shares.


Common Mistakes

  1. Mutating a struct through a foreach variable or a collection indexer. You are editing a copy. Use an array, a span, or read-mutate-write-back.
  2. Believing "structs are on the stack". A struct field of a class is on the heap, inside its owner. Where it lives depends on where it is declared.
  3. Boxing in hot paths. Assigning a struct to object, storing it in a non-generic collection, or formatting it into a params object[] allocates every time.
  4. Making a big struct and passing it around by value. Beyond roughly 16-24 bytes the copying costs more than a reference would. Either shrink it or make it a class.
  5. Using in on a non-readonly struct. The compiler inserts a defensive copy before every member call, so the optimisation backfires. Mark the struct readonly struct.
  6. Holding a Span past its storage. A span over a stackalloc buffer or a list's backing array is only valid while that storage is; resizing the list or returning from the method invalidates it.
  7. Comparing reference types with == and expecting value semantics. Without an override you are asking whether two notes name the same crate, not whether the crates match.
  8. Benchmarking the first run. Tiered compilation means early iterations execute unoptimised code. Warm up, then measure — or use a harness like BenchmarkDotNet that does it for you.

Best Practices

  • Default to class. Reach for struct only when the type is small, logically a single value, and allocated in quantity.
  • When you do write a struct, write readonly record struct unless you have a measured reason not to — it removes the copy traps and the defensive copies at once.
  • Keep structs at or below about 16 bytes for by-value passing; above that, use in on a readonly struct or switch to a class.
  • Store bulk value data in arrays or List<T> and iterate with a Span<T> when you need to mutate in place.
  • Avoid boxing on hot paths: prefer generics over object, and interpolated strings or ToString() over params object[] formatting.
  • Use stackalloc for small, fixed-size scratch buffers and ArrayPool<T> for large ones; never size a stackalloc from untrusted input.
  • Free every GCHandle in a finally, and keep pinned regions as short as possible so the collector can still compact.
  • Confirm memory hypotheses with a profiler or allocation counters rather than reasoning alone — the runtime optimises more than you expect.

Practice Exercises

  1. Build Point as a struct and Box as a class, fill an array of one million of each with the same values, and time a loop that sums their X fields. Explain the difference in terms of contiguous storage versus pointer-chasing.
  2. Write a method that takes List<Counter> and increments every element's Hits, three ways: copy-back, CollectionsMarshal.AsSpan, and converting Counter to a class. Compare the code and state which you would ship and why.
  3. Demonstrate boxing costs. Sum one million int values through an IEnumerable<int>, then through an ArrayList, then through a plain int[]. Report the timings and identify where the allocations came from.
  4. Create a large struct with eight long fields. Pass it to a method one million times by value, by in as a non-readonly struct, and by in as a readonly struct. Explain why the middle case is not the fastest.