Garbage Collection
Context: What is Garbage Collection? In .NET, the Garbage Collector (GC) is an automatic memory manager. It runs on a dedicated thread and tracks all managed objects allocated on the managed heap. When an object is no longer referenced by any root (local variables, static fields, CPU registers, etc.), the GC considers it garbage and reclaims its memory. This eliminates most memory leaks and dangling pointer bugs. The GC uses sophisticated heuristics to balance memory usage, application throughput, and pause times.
Usage Example
Section titled “Usage Example”using System;
public class GCDemo{ public static void ShowGenerations() { object obj = new object(); Console.WriteLine(GC.GetGeneration(obj)); // Current generation (0) GC.Collect(); // Force a collection (not recommended in production) Console.WriteLine(GC.GetGeneration(obj)); // Generation after collection }}Output console
Section titled “Output console”dotnet run01Important notes
Section titled “Important notes”- Automatic – You never call
freeordelete. - Non‑deterministic – The GC runs when needed (memory pressure) or heuristically.
- Generational – New objects are collected more frequently than old ones.
- Compacting – The GC moves live objects to reduce fragmentation.
Real‑world usage example
Section titled “Real‑world usage example”Large file processing – Reading a huge file line by line with StreamReader allocates many small objects (strings). Understanding GC helps you reuse buffers or use Span<T> to reduce allocations, avoiding frequent Gen0 collections.
See .NET docs on Garbage Collection.