stack · Main()managed heapgen 2gen 1gen 0LOHfreeOrder? aOrder? bint g1var a = new Order(1);2var b = new Order(2);3b = null;4GC.Collect(0);5int g = GC.GetGeneration(a);6Console.WriteLine(g);7record Order(int Id);GC0xA0000x8000Order(1)0xA040Order(2)85,000 bytesbyte[85000]nextnew0xA000new0xA040nullCollect(0)0x800011
Violet card: the program; a highlighted line is the one runningBlue cells: locals on the stack (the roots); khaki blocks: objects on the heap, in their generationArrows: references; tokens: new, addresses, null, the mark and the resultIn front: the code card Program.cs, the garbage collector (GC) and the console. At the back: Main's stack frame with the locals a, b and g, and the managed heap with gen 2, gen 1, gen 0 and the large object heap (LOH). new places each object at gen 0's allocation pointer (the flag) and the local keeps its address; the arrows are references. b = null leaves Order(2) unreachable. GC.Collect(0) pauses the program; the GC marks what the roots reach, reclaims Order(2), moves Order(1) into gen 1 and updates a. GetGeneration(a) then returns 1. The addresses (0xA000, 0xA040, 0x8000) are made up and shortened, and the gaps between them are not to scale.

Allocation

  1. A C# program keeps data in two places. Locals live in the method's stack frame. Objects made with new live on the managed heap, memory the CLR owns. A local like a holds only a reference: the object's address.

A gen 0 collection

Generations

What happens

// step 1/10 · two-places
stack frame   Main's locals: a, b, g
              gone when the method returns
managed heap  every object made with new
              the CLR owns it; the garbage collector (GC) frees it
a reference   the address of an object on the heap

The addresses (0xA000, 0xA040, 0x8000) are made up and shortened, and the gaps between them are not to scale. The picture shows the classic layout: survivors slide into gen 1. Since .NET 7 the heap is organised in regions, and a whole gen 0 region can also simply become gen 1; the GC may also sweep without compacting. Either way the object survives and its generation becomes 1.