Events
Learn how C# events let objects notify subscribers when something happens, using the event keyword.
What is an Event?
An event is a special kind of delegate that implements the publish-subscribe pattern: one object announces "something happened," and any number of other objects can subscribe to react to it.
Declaring and Raising an Event
class Order{ public event Action<string> OrderShipped;
public void Ship() { Console.WriteLine("Shipping order..."); OrderShipped?.Invoke("Order #1234"); // raise the event }}Subscribing to an Event
var order = new Order();order.OrderShipped += (id) => Console.WriteLine($"Email: {id} has shipped!");order.OrderShipped += (id) => Console.WriteLine($"SMS: {id} is on its way.");
order.Ship();Output
Click Run to see what this code prints.
The ?. Null-Conditional Operator
OrderShipped?.Invoke(...) safely does nothing if no one has subscribed — without the `?.`, invoking a null event would throw a NullReferenceException.
FAQs
An event is a delegate with restricted access — outside code can subscribe (+=) and unsubscribe (-=), but only the declaring class can raise (invoke) it.
Summary
- Events implement the publish-subscribe pattern on top of delegates.
- Multiple subscribers can react to a single event.
- Always use `?.Invoke()` to raise an event safely.