Sobes.tech
Junior — Middle

Can you give an example of a situation in C# where the system fails to properly free memory, leading to leaks?

sobes.tech AI

Answer from AI

In C#, memory leaks can occur despite the presence of a garbage collector when objects remain accessible due to references that are not released.

An example situation — using events and delegates:

If an object subscribes to another object's event but does not unsubscribe, it continues to be held in memory even if it is no longer needed.

class Publisher {
    public event EventHandler OnChange;

    public void Raise() {
        OnChange?.Invoke(this, EventArgs.Empty);
    }
}

class Subscriber {
    public Subscriber(Publisher pub) {
        pub.OnChange += HandleChange;
    }

    void HandleChange(object sender, EventArgs e) {
        // handle
    }
}
// Usage
var pub = new Publisher();
var sub = new Subscriber(pub);

// If sub is no longer needed but did not unsubscribe from pub.OnChange,
// the garbage collector cannot free sub, leading to a leak.

To avoid leaks, explicitly unsubscribe from events or use weak references.

Can you give an example of a situation in C# where… - sobes.tech