Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 23

    Stack vs Heap in .NET: Where C# Values Really Live

    What this lesson teaches

    C# structs do not have one fixed storage location. Stack vs heap depends on what contains the value, not just its type.

    The short answer is: structs are not stored on the stack as a rule. A struct inside a class object lives inside that object. In our measurement, Point[1000] allocates 16,024 bytes: 16,000 bytes of element data plus array overhead.

    We will follow values through those containers, then measure how many bytes each example creates. Afterwards, you can explain:

    • Where a struct field and a struct array element live.
    • Why new Point() need not create a separate object.
    • What changes when a local is captured or used across await.
    • Why converting a nullable integer to object can create an object—or produce null.

    Stack vs heap: storage follows the container

    A thread is a path of execution through your program. Its stack holds records of active method calls, called call frames, and can also hold temporary data.

    The managed heap is memory where .NET normally creates objects. An allocation reserves memory for something, such as a new object.

    The garbage collector, or GC, reclaims managed-heap memory occupied by objects your program can no longer reach. It does not free an object simply because the method that created it returns.

    Stack frames are removed in last-in, first-out order: when a method returns, its frame's memory becomes available for reuse without a GC collection. An ordinary uncaptured struct local usually lives in that frame, while heap objects remain until the GC reclaims them.

    You already know the copying rule: a struct is a value type, while a class is a reference type. A reference identifies an object rather than containing that object's data.

    For storage, ask a different question: what contains this value?

    A field is a variable belonging to a class or struct. A struct field is stored inline, meaning directly inside its container, as described in Choosing Between Class and Struct.

    In the measurement below, a Holder containing a Point allocates the same 32 bytes as a PointClass containing two doubles.

    flowchart TD
        H["Managed heap"] -->|contains| C["Holder object"]
        C -->|contains inline| P["Point field"]
        P -->|contains inline| D["X and Y fields"]

    The same reasoning works for other containers:

    ContainerWhere the struct's data goes
    Local variableUsually in the method's stack frame or a register; elsewhere if captured or needed after await
    Field of an ordinary heap objectInside that object
    Element of a heap arrayInside the array
    BoxInside the box object

    For an int, boxing means converting it to an object containing a copy of the integer. That object is called a box. Microsoft's Boxing and Unboxing page explains the conversion.

    A class object normally lives on the managed heap. The reference to it is stored somewhere else: a local reference usually sits on the stack or in a register, and a reference field sits inside the object that holds it.

    The mistake to avoid. Do not draw every struct as a separate stack object. A struct field belongs inside its container, and creating that field needs no separate object.

    In an interview, say: “The stack is per-thread memory for method calls. Frames are removed automatically in last-in, first-out order when methods return. The managed heap is shared memory for objects, reclaimed by the GC when objects become unreachable. Structs follow their containers, so a struct field in a heap object is inside that object.”

    What can live on the thread stack?

    The stack holds call frames. It can also hold uncaptured locals, buffers created with stackalloc, and locals whose types are declared with ref struct.

    A buffer is a region used to hold a sequence of data. stackalloc reserves a buffer associated with the current method's execution instead of creating a managed array.

    A ref struct is a value type with restrictions that prevent it from being stored in ordinary heap objects. Those restrictions help keep references to short-lived memory from outliving that memory.

    However, a local does not always get its own place in the method's call frame on the stack. A register is a small storage location inside the processor.

    Two other cases explain why “local means stack” fails:

    • A lambda is a function expression, often written with =>. When it uses an outside local, it captures that variable. A closure object holds captured variables. See capture of outer variables in lambda expressions.
    • An async method can pause at an incomplete operation using await. Its state machine is the compiler-generated machinery that remembers where to continue.

    Usually, the compiler moves captured locals into a hidden class object on the heap. Locals needed across await become fields of the async state machine, which moves to the heap when the method really pauses.

    The following example checks both lifetimes. A delegate is an object you can use to call a method; Func<int> describes one that returns an integer. Task represents an operation that may finish later. TaskCompletionSource lets this example decide when that operation finishes.

    C#Runs
    Func<int> counter = CreateCounter();
    Console.WriteLine($"Captured count: {counter()}");
    Console.WriteLine($"Captured count: {counter()}");
    
    var picture = new CounterStorage();
    Console.WriteLine($"Class picture: {picture.Next()}, {picture.Next()}");
    
    var completion = new TaskCompletionSource<bool>();
    Task<int> pending = ReadAfterPause(completion.Task);
    Console.WriteLine($"Paused: {!pending.IsCompleted}");
    completion.SetResult(true);
    Console.WriteLine($"After await: {await pending}");
    
    static Func<int> CreateCounter()
    {
        int count = 0;
        return () => ++count;
    }
    
    static async Task<int> ReadAfterPause(Task pause)
    {
        int count = 42;
        await pause;
        return count;
    }
    
    // A simplified picture, not the compiler's exact generated code.
    class CounterStorage
    {
        public int count;
        public int Next() => ++count;
    }
    Output
    Captured count: 1
    Captured count: 2
    Class picture: 1, 2
    Paused: True
    After await: 42

    The captured count remains available after CreateCounter returns: calling the returned function prints 1, then 2. CounterStorage shows the same idea with an explicit field. Its instance is created on the heap in the ordinary implementation.

    ReadAfterPause pauses at the unfinished task. After the task completes, its local count is still there, so it returns 42.

    The mistake to avoid. A declaration inside a method does not prove that its data stays on that method's stack. Capturing a local, or pausing at await, can require storage that lives longer than the method call.

    In an interview, say: “The compiler usually moves captured locals into fields of a generated closure class on the heap. Locals needed across await become fields of the async state machine, which moves to the heap when the method pauses. A local declaration alone therefore does not tell you where its data lives.”

    Measure the storage matrix

    The runtime is the .NET machinery that executes your program. Its JIT compiler translates methods into processor instructions while the program runs.

    The JIT can avoid some heap allocations. To measure the ordinary object cases here, we make the objects escape: remain accessible outside the method creating them. We do that by storing them in static fields. We count the bytes this thread allocates over 1,000 calls, after one call outside the count; console output stays outside it.

    The program uses these small types:

    • Point contains two doubles.
    • PointClass contains the same two doubles, but is a class.
    • Holder contains a Point field.
    • ReferencePoint is a struct containing a reference to a PointClass.

    int? is a nullable value type: it can hold an integer or have no value.

    Before running, predict which rows report zero bytes. Also predict whether an empty PointClass[1000] creates any PointClass objects.

    C#Runs
    #nullable enable
    using System;
    using System.Runtime.CompilerServices;
    
    public static class Program
    {
        private static object? objectSink;
        private static ReferencePoint referenceSink;
        private static double numberSink;
    
        public static void Main()
        {
            string[] labels =
            {
                "local int",
                "local Point",
                "PointClass object",
                "class holding Point",
                "struct holding reference",
                "Point[1000]",
                "PointClass[1000] empty",
                "PointClass[1000] filled",
                "boxed Point",
                "boxed int? with value",
                "boxed int? without value"
            };
    
            for (int row = 0; row < labels.Length; row++)
            {
                Measure(row, labels[row]);
            }
    
            GC.KeepAlive(objectSink);
            GC.KeepAlive(referenceSink.Target);
            Console.WriteLine($"Last numeric result: {numberSink:F0}");
        }
    
        private static void Measure(int row, string label)
        {
            const int calls = 1000;
            Work(row);
            long before = GC.GetAllocatedBytesForCurrentThread();
            for (int i = 0; i < calls; i++)
            {
                Work(row);
            }
            long bytes = GC.GetAllocatedBytesForCurrentThread() - before;
            Console.WriteLine($"{label}: {bytes / calls} B/call");
        }
    
        [MethodImpl(MethodImplOptions.AggressiveOptimization)]
        private static void Work(int row)
        {
            switch (row)
            {
                case 0:
                    int local = 42;
                    numberSink = local;
                    break;
                case 1:
                    Point point = new Point { X = 1, Y = 2 };
                    numberSink = point.X + point.Y;
                    break;
                case 2:
                    objectSink = new PointClass { X = 1, Y = 2 };
                    break;
                case 3:
                    objectSink = new Holder
                    {
                        Value = new Point { X = 1, Y = 2 }
                    };
                    break;
                case 4:
                    referenceSink = new ReferencePoint
                    {
                        Target = new PointClass { X = 1, Y = 2 }
                    };
                    break;
                case 5:
                    objectSink = new Point[1000];
                    break;
                case 6:
                    objectSink = new PointClass[1000];
                    break;
                case 7:
                    var points = new PointClass[1000];
                    for (int i = 0; i < points.Length; i++)
                    {
                        points[i] = new PointClass { X = 1, Y = 2 };
                    }
                    objectSink = points;
                    break;
                case 8:
                    objectSink = new Point { X = 1, Y = 2 };
                    break;
                case 9:
                    int? present = 42;
                    objectSink = present;
                    break;
                case 10:
                    int? absent = null;
                    objectSink = absent;
                    break;
            }
        }
    
        public struct Point
        {
            public double X;
            public double Y;
        }
    
        public sealed class PointClass
        {
            public double X;
            public double Y;
        }
    
        public sealed class Holder
        {
            public Point Value;
        }
    
        public struct ReferencePoint
        {
            public PointClass? Target;
        }
    }
    Output
    local int: 0 B/call
    local Point: 0 B/call
    PointClass object: 32 B/call
    class holding Point: 32 B/call
    struct holding reference: 32 B/call
    Point[1000]: 16024 B/call
    PointClass[1000] empty: 8024 B/call
    PointClass[1000] filled: 40024 B/call
    boxed Point: 32 B/call
    boxed int? with value: 24 B/call
    boxed int? without value: 0 B/call
    Last numeric result: 3

    How to read the rows

    The reference measurements for .NET 10.0.12, CoreCLR x64, are below. CoreCLR is the usual .NET execution engine; x64 means the 64-bit processor architecture used for this run. These object sizes and layouts are implementation details, not C# rules.

    RowBytes per callWhat was created
    Local int0No heap object
    Local Point0No heap object
    PointClass object32One object
    Class holding Point32One object with an inline field
    Struct holding reference32The referenced PointClass, not a box for the struct
    Point[1000]16,024One array containing all 1,000 structs
    Empty PointClass[1000]8,024One array containing 1,000 null references
    Filled PointClass[1000]40,024The reference array plus 1,000 objects
    Boxed Point32One box containing a copy
    Boxed int?, with value24One boxed int
    Boxed int?, without value0No object; the result is null

    Point contains 16 bytes of fields. The struct array therefore contains 16,000 bytes of element data, plus 24 bytes of array overhead in this x64 run. Those extra bytes hold the object header, a pointer to the type information, and the array length.

    For ordinary objects in this run, the header and type pointer take 16 bytes. That makes PointClass 16 + 16 = 32 bytes. A boxed int needs 16 + 4 bytes, rounded up to 24 bytes to meet the runtime's storage boundary.

    The filled class array adds 1,000 separate 32-byte objects to the 8,024-byte reference array.

    The mistake to avoid. Zero allocated bytes means no measured managed-heap allocation. It does not prove that a value was stored on the stack.

    In an interview, say: “A struct array stores its elements inline. A class array stores references, and creating the array does not create the referenced objects. A struct field inside a class also needs no separate object.”

    Do value types avoid the garbage collector?

    An inline struct does not need its own object, but that does not make everything inside it irrelevant to the GC.

    Look at the ReferencePoint row. The struct itself goes into the static struct field. Its Target refers to a separately allocated PointClass object.

    Replacing a class with a struct does not make its reference fields invisible to the GC.

    A root is a starting location the GC uses to find reachable objects. Static fields, some locals, and processor registers can provide roots. From those starting points, the GC follows references through objects, including references held in their struct fields.

    Boxing creates another connection to the GC: a box is an object that the GC manages.

    Nullable boxing has a special rule. If an int? has no value, converting it to object produces null. If it has a value, the conversion boxes the contained int, not a Nullable<int> wrapper.

    Read Microsoft's fundamentals of garbage collection for how roots and reachable objects determine what survives.

    The mistake to avoid. “Value types avoid the GC” is too broad. Inline values avoid separate objects, but references inside them still matter, and boxing creates objects.

    In an interview, say: “Inline structs need no separate object, but the GC follows references they contain. Boxed values are objects. Boxing an int? without a value gives null; with a value, it boxes the int.”

    Does new always allocate?

    No. In the local Point row, new Point initializes a struct value. It does not itself require a separate heap object.

    Compare that with the boxed Point row. Both construct the same struct, but assigning it to an object field requires boxing. The conversion introduces the object allocation.

    Even class construction is not an unconditional promise of a heap allocation in the final generated program.

    Escape analysis is the JIT's work to determine whether an object can be accessed beyond the scope where it was created. If it cannot escape, the JIT may put it on the stack or replace it with its individual field values.

    Starting in .NET 9, the 64-bit JIT can put a box that does not escape on the stack instead of the heap. .NET 10 extends stack allocation to small arrays and delegates. These are optimization opportunities, not guarantees for every eligible-looking example.

    The .NET 10 runtime notes explain the small-array, delegate, and local-struct-field improvements.

    The mistake to avoid. Do not count new expressions to predict allocated bytes. Struct initialization, boxing, constructor work, and JIT optimization affect the result differently.

    In an interview, say: “No. New on a struct initializes its value without inherently creating a heap object. Classes normally create heap objects, but the JIT may stack-allocate or eliminate a non-escaping object. That is an optimization, not a language rule.”

    Check yourself

    A heap-allocated Holder object has a Point field containing two doubles. Where are those doubles stored?

    A Inline inside the Holder object
    B In a separate Point object on the stack
    C In two boxes, one for each double
    D Always in processor registers
    Show answer

    Correct answer: A

    The Point field is part of its containing object, so its doubles sit inside the Holder. No separate Point object or box is required.

    PointClass is a class. What does new PointClass[1000] create?

    A 1,000 new PointClass objects
    B 1,000 boxed PointClass copies
    C One array of null references
    D Nothing until an element is read
    Show answer

    Correct answer: C

    A class array stores references. Creating it allocates one array of 1,000 null references (8,024 bytes in the x64 run above); each PointClass object exists only after you create and assign one.

    Going deeper

    A struct constructor can itself create other objects. “Struct initialization needs no box” does not mean “everything the constructor does is allocation-free.”

    A ref struct also does not promise that all the data it describes is on the stack. For example, Span<T> describes a contiguous region of elements and can describe part of a managed array. Its restrictions apply to the span value, not a universal storage location for the elements.

    String literals and the object returned by typeof(int) live on a separate frozen heap that the GC never collects or moves; GC.GetGeneration reports int.MaxValue for them. Large Objects and Pinning in .NET shows this.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·