Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Event Usage: Declaring, Raising, and Handling Events

Learn how to declare, raise, and handle events in C# with practical examples, thread-safety considerations, and memory-leak prevention.

~5 min readC#
#C##Events#Delegates#EventHandler
A diagram showing a publisher object raising an event to multiple subscriber handlers in C#.

In C#, events are a language-level notification mechanism built on delegates. To use events effectively, you need to know how to declare, raise, and subscribe to them without breaking encapsulation or leaking memory.

Declaring an Event and Raising It

An event is a member that a class uses to send a notification when something happens. The event is backed by a delegate, which defines the signature of the handlers that can subscribe. The simplest declaration uses the EventHandler delegate, which carries no custom data:

csharp
public class TemperatureSensor { public event EventHandler? TemperatureChanged; }

The ? indicates that the event may have no subscribers, which is important for safe invocation. To raise the event from inside the class, invoke it like a method, but only if it is not null:

csharp
private void OnTemperatureChanged() { TemperatureChanged?.Invoke(this, EventArgs.Empty); }

The ?.Invoke call is the standard way to raise an event. It invokes each handler in the order the handlers were added. The sender is typically this, and the second argument carries event-specific data. For a simple notification, EventArgs.Empty suffices.

Subscribing and Unsubscribing Handlers

Subscribers attach a method to the event using += and detach with -=. The method must match the delegate signature. For EventHandler, that means a method returning void and accepting object? sender and EventArgs e.

csharp
var sensor = new TemperatureSensor(); sensor.TemperatureChanged += OnTemperatureChanged; void OnTemperatureChanged(object? sender, EventArgs e) { Console.WriteLine("Temperature changed."); }

You can also use a lambda expression, but be careful: a lambda expression usually creates a new delegate instance, so you cannot remove it later unless you keep a reference. For one-time subscriptions, a lambda is fine; for long-lived subscriptions, a named method is easier to manage.

Unsubscribing is symmetric:

csharp
sensor.TemperatureChanged -= OnTemperatureChanged;

After this, the handler will no longer be called. If you unsubscribe a handler that was never added, the operation is a no-op and does not throw.

How Events Differ from Delegates

An event is not just a public delegate field. The compiler generates a private delegate field and exposes the event with add and remove accessors, similar to properties. This means external code can only subscribe or unsubscribe; it cannot invoke the event or replace the delegate list. That restriction is intentional: the publishing class controls when the event is raised.

csharp
public class Example { public event EventHandler? MyEvent; }

From outside Example, an expression such as example.MyEvent?.Invoke(example, EventArgs.Empty) does not compile; only += and -= are allowed. If you declared a public delegate field instead, any code could invoke it or overwrite the invocation list, breaking encapsulation. Events enforce the publisher-subscriber contract.

Thread Safety When Raising Events

Raising a field-like event with ?.Invoke avoids the classic race of checking for null and then invoking a delegate that has become null: the compiler reads the delegate reference once and invokes the captured delegate instance. This does not make the handler methods themselves thread-safe. If handlers access shared state, they need their own synchronization.

Before C# 6, or when you want to make the captured reference explicit, you can copy the delegate reference to a local variable before checking:

csharp
var handler = TemperatureChanged; if (handler != null) { handler(this, EventArgs.Empty); }

This pattern makes the captured reference explicit and is the form shown in older .NET documentation. It still does not synchronize the handlers themselves.

Preventing Memory Leaks from Event Subscriptions

A common problem in event-driven code is a memory leak caused by a subscriber that is never unsubscribed. The publisher holds a strong reference to each subscriber through the delegate's invocation list. If the publisher is long-lived and the subscriber is short-lived, the publisher keeps the subscriber alive after it is no longer needed. If the subscriber additionally keeps a reference back to the publisher, the publisher's lifetime can also be extended, but that is a separate object-lifetime concern.

For example, if a UI control subscribes to a service event and the control is closed but not unsubscribed, the service still references the control, preventing its memory from being reclaimed. The fix is to unsubscribe when the subscriber is no longer needed, typically in a Dispose method.

csharp
public class Subscriber : IDisposable { private readonly Service _service; public Subscriber(Service service) { _service = service; _service.StatusChanged += OnStatusChanged; } public void Dispose() { _service.StatusChanged -= OnStatusChanged; } }

If you cannot guarantee unsubscription, consider using weak event patterns, but they add complexity. For most applications, disciplined subscription management is sufficient.

Using EventHandler<T> and Custom EventArgs

When an event needs to carry data, use EventHandler<TEventArgs> where TEventArgs derives from EventArgs. This generic version avoids the need to define a custom delegate for every event.

csharp
public class TemperatureChangedEventArgs : EventArgs { public double NewTemperature { get; } public TemperatureChangedEventArgs(double newTemperature) { NewTemperature = newTemperature; } } public class TemperatureSensor { public event EventHandler<TemperatureChangedEventArgs>? TemperatureChanged; private void RaiseTemperatureChanged(double newTemp) { TemperatureChanged?.Invoke(this, new TemperatureChangedEventArgs(newTemp)); } }

Subscribers then receive the typed argument and can access its properties directly. This is the standard pattern for events that carry state. Avoid reusing EventArgs for data; create a dedicated class so the contract is explicit.

Handling Exceptions in Event Handlers

An exception thrown inside an event handler propagates back to the code that raised the event. This means one faulty subscriber can break the entire notification loop. The publisher does not automatically catch exceptions from handlers, and the remaining subscribers after the throwing one will not be called.

To isolate failures, you can wrap each invocation in a try-catch inside the raising method, but that changes the semantics. A more common approach is to let exceptions bubble up and require handlers to be well-behaved. If you need fault isolation, you can invoke handlers manually:

csharp
private void RaiseTemperatureChanged(double newTemp) { var handler = TemperatureChanged; if (handler == null) return; var args = new TemperatureChangedEventArgs(newTemp); foreach (EventHandler<TemperatureChangedEventArgs> subscriber in handler.GetInvocationList()) { try { subscriber(this, args); } catch (Exception ex) { // Log and continue with the next subscriber } } }

This gives you control over error handling, but it also means the publisher is responsible for handling failures, which may not be desirable. Weigh the tradeoff based on your application's requirements.

Design Considerations for Event-Driven Code

Events are most useful when the publisher does not need to know who is listening or how many. This decoupling is valuable in UI frameworks, messaging systems, and observable models. However, events also introduce hidden dependencies: the publisher cannot control the order of handlers or guarantee that any handler will succeed.

When designing an event API, keep the signature simple. Use EventHandler<T> for data-bearing events and avoid defining custom delegate types unless you need a different return value or more parameters. Prefer void return types because event handlers are notifications, not queries. If you need a return value, consider a different pattern, such as a callback or a service interface.

Also consider whether an event is the right tool. If you need to cancel an operation or receive a result, events are not a good fit. In those cases, use a delegate, an interface, or an async method. Events are for one-way notifications, and their usage should reflect that.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.