Phase 2 of 30 · Topic 2.1

Stack vs Managed Heap: Value Types vs Reference Types

1Concept

Value types (`struct`, `int`, `enum`) store their data directly in-place (on the thread call stack or embedded within containing classes). Reference types (`class`, `string`, `record`) store a memory pointer pointing to the heap-allocated instance.

2Architecture Diagram

[ Thread Call Stack ]                      [ Managed GC Heap ]
┌────────────────────────────┐              ┌────────────────────────────┐
│ int count = 42             │              │ SampleClass Instance       │
│ PointStruct (X=10, Y=20)   │              │ ├── SyncBlockIndex (8B)    │
│ ClassRef ptr ──────────────┼─────────────>│ ├── MethodTable Ptr (8B)   │
└────────────────────────────┘              │ └── Data Fields (Payload)  │
                                            └────────────────────────────┘

3Code Example

C# 13 & .NET 9
using System;

public struct PointVal { public int X; public int Y; }
public class PointRef { public int X; public int Y; }

public class StackVsHeapDemo
{
    public static void Main()
    {
        PointVal v1 = new PointVal { X = 10, Y = 20 };
        PointVal v2 = v1; // Copy by value
        v2.X = 99;

        PointRef r1 = new PointRef { X = 10, Y = 20 };
        PointRef r2 = r1; // Copy pointer reference
        r2.X = 99;

        Console.WriteLine($"Struct v1.X: {v1.X} (Unchanged, independent stack copy)");
        Console.WriteLine($"Class r1.X: {r1.X} (Mutated, shared heap instance)");
    }
}

4Expected Output

Struct v1.X: 10 (Unchanged, independent stack copy)
Class r1.X: 99 (Mutated, shared heap instance)

5Key Takeaways

  • Value type assignment copies the entire payload byte-by-byte.
  • Reference type assignment only copies the 8-byte pointer.
  • Stack memory deallocation is O(1) instantaneous on function exit; Heap memory requires Garbage Collection.