C# › Memory & Garbage Collection
How does garbage collection in .NET work, and what three phases does a collection cycle go through?
BeginnerAnswer
The .NET garbage collector automatically reclaims memory occupied by objects no longer reachable by the application, removing the need for manual memory management -- a collection cycle generally proceeds through marking (scanning the object graph from GC roots to determine which objects are still reachable), sweeping (reclaiming the memory of unreachable objects), and compacting (moving surviving objects together to reduce fragmentation and keep allocation fast) -- this automation prevents most memory leaks but means the GC can introduce brief pauses, especially if an application allocates large numbers of short-lived objects.
public void ProcessOrders() {
for (int i = 0; i < 100_000; i++) {
var temp = new OrderDto(); // short-lived object, becomes eligible for GC almost immediately
// process temp
} // by the time this loop ends, most 'temp' instances are already unreachable garbage
}Real-world example A high-throughput API creating a new DTO object per request notices periodic latency spikes correlated with GC cycles, prompting the team to reduce unnecessary allocations (pooling objects, using structs for small data) to shrink the frequency and cost of those collection pauses.