What is garbage collection in C#?
Answer
The garbage collector (GC) is the CLR's automatic memory management system. It periodically identifies objects on the heap that are no longer reachable (no live references) and reclaims their memory — freeing developers from manual memory management (no free() like in C). The .NET GC uses a generational model with three generations: Gen 0: newly allocated, short-lived objects — collected most frequently, very fast. Gen 1: objects that survived Gen 0 collection — a buffer between Gen 0 and Gen 2. Gen 2: long-lived objects — collected infrequently, most expensive. Large Object Heap (LOH): objects ≥ 85KB, always Gen 2. GC pauses your application during collection (though .NET 5+ GC is increasingly concurrent). Tips: avoid unnecessary allocations, use Span<T> and ArrayPool<T> for hot paths, implement IDisposable for unmanaged resources.
Previous
What is the difference between Task and Thread in C#?
Next
What is IDisposable and the using statement?