Garbage Collection (GC) in C# is an automatic memory management system that tracks object references and reclaims memory from objects that/that no longer have any active references in the heap.
- The GC uses aGenerations (Gen 0, Gen 1, and Gen 2) to optimize performance by scanning shorter-lived objects more frequently.
- The Generational Hypothesis assumes most objects die young, so the GC focuses its efforts on theRecycling of Gen 0 objects.
- The GC identifies unreachable objects by traversing the object graph starting from roots like static variables, local variables, and CPU registers.
- The GC compacts the managed heap to reduce fragmentation by moving surviving objects closer together.
GC.Collect(); // Manually triggers a full garbage collection, though generally discouraged in production code.