C# EXPERTChapter 6 · C# Expert
Garbage collection generations and Span memory
The Common Language Runtime (CLR) manages memory via a Garbage Collector with three generations (Gen 0, 1, 2) for short/long-lived objects. Modern C# uses Span<T> for zero-allocation stack slices.
Worked example
using System;
class Program {
static void Main() {
Span<int> numbers = stackalloc int[] { 1, 2, 3 };
Span<int> slice = numbers.Slice(1, 2);
Console.WriteLine(slice[0]);
}
}How it reads
- Span<T> provides type-safe, contiguous memory access (stack or heap)
- stackalloc allocates memory on stack, skipping GC overhead entirely

Cloud tip: Garbage collection promotes surviving items from Generation 0 to Gen 1, and eventually to Gen 2.


