wasAsked.

What is Garbage Collection?

Agiliad Technologies Pvt Ltd · Role not specified · technical

Published

Asked in 2026 · C#

Community answers

Posted by wasAsked editorial collection

Garbage Collection (GC) is the .NET runtime feature that automatically reclaims memory used by objects that are no longer needed. It frees developers from manual memory management and prevents bugs such as memory corruption, double frees and dangling pointers. How it works, in simple terms 1. When you create an object (new Customer()), memory is allocated on the managed heap. 2. Your code holds references to objects through variables, fields and collections. 3. Periodically — mainly when the youngest generation fills up — the GC starts a collection. 4. It finds all objects still reachable from "roots" (static fields, local variables on thread stacks, CPU registers). 5. Unreachable objects are garbage; their memory is reclaimed. Surviving objects are compacted together. Generations for efficiency - Gen 0: new objects, collected very often. - Gen 1: short-lived survivors, a buffer. - Gen 2: long-lived objects, collected rarely. - Large Object Heap: objects of 85 KB or more, collected with Gen 2. Most objects die young, so collecting Gen 0 frequently is cheap and effective. What the GC does not do - It does not release unmanaged resources (files, connections, sockets) promptly. Use IDisposable and the using statement for those. - It does not prevent "logical" leaks: if you keep references (static lists, caches, event subscriptions), objects stay alive. Developer best practices - Dispose resources with using or await using. - Avoid unnecessary allocations in hot paths (string concatenation in loops, boxing, excessive LINQ). - Unsubscribe from events and limit cache sizes. - Avoid calling GC.Collect() — the runtime tunes collections better than manual calls. - Use ArrayPool<T> and Span<T> for buffers in performance-sensitive code. GC modes - Workstation GC (desktop apps) and Server GC (default for ASP.NET Core, multiple heaps for throughput), plus background GC to reduce pause times. Monitoring - dotnet-counters shows heap size and collection counts per generation; dotnet-gcdump and memory profilers help find leaks.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics