C# › Memory & Garbage Collection
What is a memory leak in a garbage-collected language like C#, given that the GC handles cleanup automatically?
IntermediateAnswer
A memory leak happens when objects remain REACHABLE (through a live reference chain from a root, like a static field, an event subscription, or a cached collection) even though the application logically no longer needs them — since the GC only collects UNREACHABLE objects, an accidentally-retained reference prevents collection indefinitely, growing memory usage over time.
public class EventPublisher {
public static event Action? OnSomethingHappened; // static event: a common leak source
}
public class Subscriber {
public Subscriber() {
EventPublisher.OnSomethingHappened += HandleEvent; // if never unsubscribed, 'this' leaks forever
}
private void HandleEvent() { }
}Real-world example Debugging a long-running service whose memory usage climbs steadily, traced back to event subscriptions that were never unsubscribed.