C# Events
An event lets an object announce that something happened — a button was clicked, a download finished, a temperature crossed a threshold — without knowing who is interested. Other objects subscribe to the event and are notified when it is raised. This publisher/subscriber pattern keeps classes loosely coupled: the publisher never needs to reference its subscribers' types.
Declaring, subscribing and raising
An event is declared with the event keyword and a delegate type, most often Action or EventHandler. Subscribers attach handlers with +=.
using System;
var kettle = new Kettle();
kettle.Boiled += () => Console.WriteLine("Subscriber 1: making tea");
kettle.Boiled += () => Console.WriteLine("Subscriber 2: turning off the stove");
kettle.Heat(60);
kettle.Heat(100);
class Kettle
{
public event Action Boiled;
public void Heat(int temperature)
{
Console.WriteLine(quot;Kettle at {temperature}°C");
if (temperature >= 100)
Boiled?.Invoke(); // raise the event (if anyone subscribed)
}
}Kettle at 60°C
Kettle at 100°C
Subscriber 1: making tea
Subscriber 2: turning off the stove
Boiled?.Invoke() uses the null-conditional operator: with no subscribers, the event is null, and raising it must not crash.
Why the event keyword?
You could use a public delegate field instead, but event restricts what outsiders can do:
| Operation | Public delegate field | event |
|---|---|---|
Subscribe += / unsubscribe -= from outside |
✔ | ✔ |
Overwrite all handlers with = from outside |
✔ (dangerous) | ✘ compile error |
| Raise it from outside the class | ✔ (dangerous) | ✘ compile error |
Only the class that declares the event can raise it, and no subscriber can accidentally remove everyone else's handlers.
The standard EventHandler pattern
.NET conventions say an event handler receives two arguments: the sender (the object that raised the event) and an event-args object with the details. Use EventHandler<TEventArgs> and a small class or record deriving from EventArgs:
using System;
var stock = new Stock("ACME", 100m);
var monitor = new PriceMonitor();
stock.PriceChanged += monitor.OnPriceChanged;
stock.PriceChanged += (sender, e) =>
{
if (e.NewPrice < e.OldPrice) Console.WriteLine(" Alert: price dropped!");
};
stock.Price = 104.5m;
stock.Price = 104.5m; // same price: no event
stock.Price = 97m;
class PriceChangedEventArgs : EventArgs
{
public decimal OldPrice { get; }
public decimal NewPrice { get; }
public PriceChangedEventArgs(decimal oldPrice, decimal newPrice) { OldPrice = oldPrice; NewPrice = newPrice; }
}
class Stock
{
private decimal price;
public string Symbol { get; }
public event EventHandler<PriceChangedEventArgs> PriceChanged;
public Stock(string symbol, decimal price) { Symbol = symbol; this.price = price; }
public decimal Price
{
get => price;
set
{
if (value == price) return;
decimal old = price;
price = value;
OnPriceChanged(new PriceChangedEventArgs(old, value));
}
}
protected virtual void OnPriceChanged(PriceChangedEventArgs e) => PriceChanged?.Invoke(this, e);
}
class PriceMonitor
{
public void OnPriceChanged(object sender, PriceChangedEventArgs e)
{
var stock = (Stock)sender;
Console.WriteLine(quot;{stock.Symbol}: {e.OldPrice} -> {e.NewPrice}");
}
}ACME: 100 -> 104.5
ACME: 104.5 -> 97
Alert: price dropped!
The protected virtual OnXxx method that raises the event is another convention: it lets subclasses customise or intercept the notification.
Unsubscribing
Remove a handler with -=. To be able to remove it, you need a reference to the same method or delegate — so store lambdas in a variable if you plan to unsubscribe them later.
using System;
var timer = new Ticker();
int ticksSeen = 0;
Action<int> counter = n => ticksSeen++;
Action<int> printer = n => Console.WriteLine(quot;tick {n}");
timer.Tick += counter;
timer.Tick += printer;
timer.Run(2);
timer.Tick -= printer; // stop printing, keep counting
timer.Run(3);
Console.WriteLine(quot;Ticks counted: {ticksSeen}");
class Ticker
{
private int number;
public event Action<int> Tick;
public void Run(int count)
{
for (int i = 0; i < count; i++)
Tick?.Invoke(++number);
}
}tick 1
tick 2
Ticks counted: 5
Note: A subscribed handler keeps its object alive as long as the publisher lives. In long-running applications, forgetting to unsubscribe from a long-lived publisher is a classic cause of memory leaks.
Where events are used
- UI frameworks (WinForms, WPF, MAUI):
button.Click += OnClick; INotifyPropertyChanged: objects announce property changes for data binding.- Domain logic: an
OrderraisesShipped, and an emailer and an inventory service react independently.
Test yourself
Which operator subscribes a handler to an event?
- =
- +=
- =>
- ==
Why is MyEvent?.Invoke() used instead of MyEvent()?
- It is faster
- It avoids a NullReferenceException when there are no subscribers
- It runs handlers in parallel
- It is required by the compiler
What can code outside the declaring class NOT do with an event?
- Subscribe with +=
- Unsubscribe with -=
- Raise (invoke) it
- Pass a lambda as a handler