wasAsked.

Explain Garbage Collection in .NET.

Capgemini · Full Stack Developer · technical

Published

Year not specified · .NET, C#

Community answers

Posted by wasAsked editorial collection

Garbage Collection (GC) in .NET automatically frees memory used by objects that are no longer reachable, so developers do not call free or delete. How it works: - Objects are allocated on the managed heap by moving a pointer, which makes allocation very fast. - When a collection runs, the GC starts from roots — static fields, local variables on thread stacks, CPU registers, GC handles — and marks every object reachable from them. - Unreachable objects are reclaimed, and surviving objects are usually compacted to remove fragmentation. Generations: - Gen 0: new, short-lived objects. Collected very frequently and cheaply. - Gen 1: a buffer between short- and long-lived objects. - Gen 2: long-lived objects (caches, singletons). Collections are rarer and more expensive. Most objects die young, so collecting Gen 0 often is efficient. Large Object Heap (LOH): objects of about 85,000 bytes or more (for example big arrays) go here. It is collected with Gen 2 and not compacted by default, so frequent large allocations can cause fragmentation. ArrayPool<T> helps by reusing large buffers. Modes: workstation vs server GC (server GC uses a heap per core and suits ASP.NET Core), and background GC, which runs Gen 2 collections concurrently to reduce pauses. Unmanaged resources: GC handles memory, not file handles, sockets or database connections. Implement IDisposable and use "using" to release them deterministically. Finalizers are a last-resort safety net and make objects survive an extra collection. Common causes of memory leaks in managed code: event handlers that are never unsubscribed, static collections that grow forever, unbounded caches, and long-lived references captured by closures. Calling GC.Collect() manually is almost never needed and usually hurts performance. Diagnose memory problems with dotnet-counters, dotnet-gcdump or a memory profiler instead.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics