Skip to content

Memory Leaks in .NET

Question

Is a memory leak possible in .NET? Provide examples.

Short interview answer

Yes. The GC reclaims only unreachable managed objects, so objects unintentionally kept reachable leak memory from the application's perspective. Common causes include event subscriptions, static caches, and unbounded collections.

Detailed answer

A managed leak means an object remains reachable even though the application no longer needs it. For example, a screen subscribes to a long-lived event source and is then closed:

publisher.Updated += screen.Refresh;

The publisher now holds the delegate, which holds the screen. The screen cannot be collected until it unsubscribes or the publisher dies. The same problem appears in unbounded static dictionaries, caches with no eviction, queued callbacks, and service singletons that retain request-specific objects. A separate class of leak is an undisposed native resource, such as a file or socket handle.

Diagnose the repeated scenario with allocation and heap tooling, then inspect the retaining reference path for an object that should have disappeared. Forcing a collection only hides timing; remove the unwanted owner, bound the cache, or dispose the resource.

Sources