Skip to content

Subscribing and unsubscribing

Context: Subscribers add their event handlers using += and remove them using -=. This prevents memory leaks when the subscriber outlives the publisher.

Button button = new Button();
button.Clicked += OnButtonClicked; // subscribe
private void OnButtonClicked(object sender, EventArgs e)
{
Console.WriteLine("Button clicked");
}
button.Clicked -= OnButtonClicked; // unsubscribe
button.Clicked += (sender, e) => Console.WriteLine("Clicked");
// Unsubscribing from lambda is tricky; store the delegate in a variable.
EventHandler handler = (s, e) => Console.WriteLine("Clicked");
button.Clicked += handler;
button.Clicked -= handler;

Dispose pattern: In long‑lived applications, always unsubscribe from events in the Dispose method to avoid memory leaks.

Example: In WinForms, controls unsubscribe from events when disposed.