1.12 — Events¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.11 Delegates · Next: 1.13 Lambdas and closures
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- An event is a delegate with restrictions. Outsiders can only subscribe (
+=) and unsubscribe (-=). They cannot replace it or fire it. - The standard shape is
EventHandler<TArgs>, and the standard way to raise it isMyEvent?.Invoke(this, args). - Forgetting to unsubscribe is a real memory leak. The publisher holds a reference to every subscriber, so subscribers never get collected.
The concept¶
An event is the "let me know when something happens" mechanism.
A newspaper subscription is the usual comparison, and it fits well. The newspaper (the publisher) does not know or care who its readers are. Readers (subscribers) sign up, receive every issue, and can cancel whenever they like. The newspaper just prints and sends.
In code: one object announces "something happened", and any number of other objects can have arranged to be told.
Events are built directly on delegates (1.11). An event is a multicast delegate wrapped in some protection.
How it works¶
Why not just a public delegate?¶
You could use a plain public delegate field:
But then anyone outside the class can do three things they should not be able to:
order.Completed = null; // wipe out everyone else's subscriptions!
order.Completed = MyHandler; // replace instead of add — same problem
order.Completed?.Invoke(order); // fire the event from outside
Adding the event keyword blocks all three:
From outside, only += and -= compile. Assignment and invocation are compile errors.
Only code inside the declaring class can raise it. That is the entire purpose of the
keyword.
The standard pattern¶
.NET convention uses EventHandler<TEventArgs>, which is a delegate shaped as
(object? sender, TEventArgs e):
public class OrderCompletedEventArgs(Guid orderId, decimal total) : EventArgs
{
public Guid OrderId { get; } = orderId;
public decimal Total { get; } = total;
}
public class OrderService
{
public event EventHandler<OrderCompletedEventArgs>? OrderCompleted;
public void Complete(Order order)
{
order.MarkComplete();
// Raise it. The ?. is essential — see below.
OrderCompleted?.Invoke(this, new OrderCompletedEventArgs(order.Id, order.Total));
}
}
Subscribing:
var service = new OrderService();
service.OrderCompleted += (sender, e) =>
Console.WriteLine($"Order {e.OrderId} completed for {e.Total:C}");
Why ?.Invoke and not just Invoke¶
If nobody has subscribed, the event field is null. Calling Invoke on it throws a
NullReferenceException.
The ?. handles that. But there is a subtler reason it is the recommended form: it also
avoids a race condition. Consider the naive version:
if (OrderCompleted != null)
OrderCompleted(this, args);
// If another thread unsubscribes the last handler BETWEEN these two lines,
// the second line throws even though we just checked.
?.Invoke reads the delegate into a temporary once and then calls it, so the check and the
call happen on the same value. Since the delegate list itself cannot change once captured,
this is safe.
The memory leak ⚠️¶
This is the part interviewers care about most, so it is worth understanding properly.
When you subscribe, the publisher stores a reference to the subscriber.
public class OrderService // long-lived — lives for the whole app
{
public event EventHandler<OrderCompletedEventArgs>? OrderCompleted;
}
public class OrderPage // short-lived — one per page view
{
public OrderPage(OrderService service)
{
service.OrderCompleted += OnCompleted; // subscribe
}
private void OnCompleted(object? s, OrderCompletedEventArgs e) { /* ... */ }
}
Now trace what happens:
OrderPagesubscribes.OrderServicenow holds a delegate.- That delegate points at the
OnCompletedmethod on that specific OrderPage object. - So
OrderServiceis holding a reference to theOrderPage. - The user closes the page. Your code drops its reference to
OrderPage. - But
OrderServiceis still holding one. The garbage collector cannot collect it. - Repeat a thousand times. You now have a thousand dead pages in memory, all still receiving events.
This is a genuine memory leak, and it is the classic one in .NET.
The fix is to unsubscribe:
public class OrderPage : IDisposable
{
private readonly OrderService _service;
public OrderPage(OrderService service)
{
_service = service;
_service.OrderCompleted += OnCompleted;
}
public void Dispose()
{
_service.OrderCompleted -= OnCompleted; // essential
}
}
And a trap inside the trap: you cannot unsubscribe a lambda this way.
service.OrderCompleted += (s, e) => DoSomething();
service.OrderCompleted -= (s, e) => DoSomething();
// Does NOTHING. These are two different lambda objects
// that happen to contain the same code.
To unsubscribe a lambda you must keep a reference to it:
EventHandler<OrderCompletedEventArgs> handler = (s, e) => DoSomething();
service.OrderCompleted += handler;
// ... later ...
service.OrderCompleted -= handler; // works — same object
Events in ASP.NET Core¶
Worth knowing: classic C# events are rare in ASP.NET Core applications. They are much more common in desktop UI code (WinForms, WPF).
The reasons are practical. Events are synchronous by default, and there is no clean way to
await an event handler. They are in-process only, so they do not survive a restart or
cross a service boundary. And the subscription lifetime does not match the request-scoped
world that ASP.NET Core lives in.
What is used instead:
- MediatR notifications for in-process publish/subscribe — see 22.10
- Domain events raised by entities and dispatched after
SaveChanges— see 22.8 - A message broker (RabbitMQ, Kafka, Azure Service Bus) for anything crossing a service boundary — see 23.4
If an interviewer asks about events in a web context, mentioning this distinction is a strong answer.
Interview questions¶
Q: What is an event and how does it differ from a delegate?
An event is a delegate with access restrictions applied. With a plain public delegate
field, any outside code could assign to it — wiping out all existing subscribers — or
invoke it, firing the event from outside the class. The event keyword restricts outside
code to += and -= only. Assignment and invocation are limited to the declaring class.
So an event is the safe, encapsulated way to expose a delegate as a notification point.
Q: How can events cause a memory leak?
When an object subscribes to an event, the publisher stores a reference to the subscriber's
method, which means it holds a reference to the subscriber object. If the publisher is
long-lived and the subscriber is short-lived, the subscriber can never be garbage collected
even after everything else has released it — because the event is still holding on. The fix
is to unsubscribe with -=, usually in Dispose. The trap is that you cannot unsubscribe
a lambda unless you stored it in a variable first, because writing the same lambda again
creates a completely different object.
Q: Why do you write MyEvent?.Invoke(...) instead of just MyEvent(...)?
Because if nobody has subscribed, the delegate is null and calling it throws. The
null-conditional operator handles that. It also avoids a race condition that the older
if (MyEvent != null) MyEvent(...) pattern has — another thread could unsubscribe the last
handler between the check and the call. ?.Invoke reads the delegate once into a temporary
and calls that, so the value it checked is the value it calls.
Q: Do you use C# events in ASP.NET Core?
Rarely. They are synchronous, you cannot properly await a handler, and they only work within a single process, so they do not fit a web application well. For in-process notifications I would use MediatR notifications or domain events dispatched after saving changes. For anything crossing a service boundary I would use a message broker, because that also gives you durability and retries. Events are much more at home in desktop UI frameworks.
Traps ⚠️¶
- Forgetting to unsubscribe leaks the subscriber. The publisher keeps it alive.
- You cannot unsubscribe a lambda by writing it again. Store it in a variable.
- A throwing handler stops the remaining handlers. They are invoked in order and the exception propagates.
- Handlers run on whatever thread raised the event. There is no automatic marshalling and no automatic thread safety.
async voidevent handlers swallow exceptions and can crash the process. This is one of the very few placesasync voidis tolerated, and it still needs a try/catch around the whole body. See 2.15.- Events cannot be awaited. If handlers need to do async work, an event is the wrong tool.
Related¶
- 1.11 Delegates — what an event is built on
- 1.13 Closures — why lambda handlers capture more than you expect
- 1.21 IDisposable — where unsubscribing belongs
- 3.5 Memory leaks — events as a leading cause
- 22.10 MediatR — the modern in-process alternative