Events
An event is a standardized way for a class (the publisherThe class that owns the event and raises it.) to notify other classes (subscribersThe classes that listen for the event and react to it.) when something significant happens.
Events are built on delegatesDelegatesA type-safe function pointer, so a method can be passed around like any other value.Opens in a new tab, with one extra layer of encapsulation: only the declaring class can invoke the event, and subscribing (+=) and unsubscribing (-=) are controlled.
In code
The comments in this example number the three steps. Line 4 is the delegate the event uses. Line 7 declares the event with it. Line 17 is the method that raises the event. The commented subscriber at the bottom attaches a handler with +=.
public class Button{ // 1. Define a delegate for the event public delegate void ClickHandler(object sender, EventArgs e); // 2. Declare the event using the delegate public event ClickHandler Clicked; // 3. Method to raise the event public void SimulateClick() { OnClicked(EventArgs.Empty); } protected virtual void OnClicked(EventArgs e) { Clicked?.Invoke(this, e); // Safely invoke the event }} // Subscriber// Button myButton = new Button();// myButton.Clicked += (sender, args) => Console.WriteLine("Button was clicked!");// myButton.SimulateClick();Where it matters
Events are crucial for building loosely coupled systems, particularly in UI programming, like button clicks and mouse movements. They are also how the Observer design pattern gets implemented. Objects can react to changes in other objects without depending on them directly.
Event handler delegates return void, so an event handler that awaits has to be async void. That is the one place it’s accepted, and it comes with rules of its own: see why async void is dangerousWhy async void is dangerousIt discards the Task, so the caller cannot await it or catch its exceptions.Opens in a new tab.
What goes in the e of the standard handler signature is in EventArgs and event dataEventArgs and event dataThe base class for the data an event carries.Opens in a new tab.
Sources
- Understanding Delegates in C#, ScholarHat · accessed May 16, 2025