Subscribing and unsubscribing
Context: Subscribers add their event handlers using += and remove them using -=. This prevents memory leaks when the subscriber outlives the publisher.
Subscribing
Section titled “Subscribing”Button button = new Button();button.Clicked += OnButtonClicked; // subscribe
private void OnButtonClicked(object sender, EventArgs e){ Console.WriteLine("Button clicked");}Unsubscribing
Section titled “Unsubscribing”button.Clicked -= OnButtonClicked; // unsubscribeUsing lambda expressions
Section titled “Using lambda expressions”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;Real-world usage example
Section titled “Real-world usage example”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.