Skip to content
dreamcode
dreamcode
Map
C# Internals
Lesson 21 of 21
+15 XP on finish
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.

Check your understanding

0 / 2

Answer all 2 to complete this lesson and earn 15 XP.

  1. 1. Which GC generation contains short-lived temporary objects?
  2. 2. What is a primary benefit of using Span<T> in C#?
Answer every question to unlock the next lesson.