Language 4 of 10 · Topic 0.8

CLR Memory Model: Generational GC (Gen 0, 1, 2, LOH) & IDisposable (using)

1Concept

.NET Garbage Collector uses 3 generational pools (Gen 0 ephemeral, Gen 1 buffer, Gen 2 long-lived) and the Large Object Heap (LOH for objects >= 85,000 bytes). IDisposable and using declarations ensure deterministic release of unmanaged resources (database handles, files).

2Architecture Diagram

+------------------------------------------------------------+
|                       .NET CLR HEAP                        |
|  [ Gen 0 (Small, Fast) ] ──► [ Gen 1 ] ──► [ Gen 2 (Old) ] |
|  [ Large Object Heap (LOH >= 85KB)                       ] |
+------------------------------------------------------------+

3Code Example

Stage 0 Language Foundations
using System;
using System.IO;

class Program
{
    static void Main()
    {
        // using declaration ensures Dispose() is called on block exit
        using var stringWriter = new StringWriter();
        stringWriter.WriteLine("CareerAI Cloud System Initialized");
        stringWriter.WriteLine("Transaction Log Stored");

        Console.WriteLine($"Writer Content:\n{stringWriter}");
        Console.WriteLine($"GC Total Memory: {GC.GetTotalMemory(false) / 1024} KB");
    } // stringWriter.Dispose() automatically called here!
}

4Expected Output

Writer Content:
CareerAI Cloud System Initialized
Transaction Log Stored

GC Total Memory: 142 KB

5Key Takeaways

  • Always use using var declarations on IDisposable objects to prevent resource leaks.
  • Gen 0 collections take fractions of a millisecond; Gen 2 full collections are expensive.
  • Avoid allocating temporary objects >= 85KB to avoid LOH fragmentation.