ZetCode

C# events

last modified November 15, 2026

This article shows how to use events in C#. We declare and raise an event, subscribe and unsubscribe handlers, write custom event accessors, put events in an interface, and look at what happens when a handler throws.

An event is a member that lets a class notify other code when something happens. The class that owns the event is the publisher; the methods that react to it are the subscribers. An event is built on a delegate: the delegate type defines the signature of the handlers, and the event controls how handlers may be added or removed. Inside the publisher, an event behaves like a delegate field; outside, only += and -= are allowed. Calling the event from another class is a compile-time error, which keeps the decision of when to raise it in the publisher.

By convention, an event handler returns void and takes two parameters: the publisher as object? and an event data object. The base class for the data is EventArgs, and the generic EventHandler<TEventArgs> delegate supplies the standard shape. For events without data, the non-generic EventHandler delegate is enough.

Declaring and raising an event

A field-like event is declared with the event keyword and a delegate type. The compiler creates a private backing delegate and the add and remove accessors. The publisher raises the event with ?. so that an event without subscribers does not throw a NullReferenceException.

Program.cs
var stock = new Stock("AAPL");
stock.PriceChanged += OnPriceChanged;

stock.UpdatePrice(189.50m);
stock.UpdatePrice(191.20m);

static void OnPriceChanged(object? sender, PriceChangedEventArgs e)
{
    Console.WriteLine($"{e.Symbol}: {e.OldPrice:F2} -> {e.NewPrice:F2}");
}

public sealed class PriceChangedEventArgs : EventArgs
{
    public PriceChangedEventArgs(string symbol, decimal oldPrice, decimal newPrice)
    {
        Symbol = symbol;
        OldPrice = oldPrice;
        NewPrice = newPrice;
    }

    public string Symbol { get; }
    public decimal OldPrice { get; }
    public decimal NewPrice { get; }
}

public sealed class Stock
{
    private decimal _price;

    public Stock(string symbol) => Symbol = symbol;

    public string Symbol { get; }

    public event EventHandler<PriceChangedEventArgs>? PriceChanged;

    public void UpdatePrice(decimal price)
    {
        if (price == _price)
        {
            return;
        }

        decimal oldPrice = _price;
        _price = price;
        PriceChanged?.Invoke(this, new PriceChangedEventArgs(Symbol, oldPrice, price));
    }
}

The Stock class exposes a PriceChanged event and a method that changes the price. The event data carries the symbol, the old price, and the new price.

PriceChanged?.Invoke(this, new PriceChangedEventArgs(Symbol, oldPrice, price));

The ?. operator invokes the delegate only when it is not null. The first argument is the publisher, this, so subscribers can tell which object raised the event. The second argument is the immutable event data. The early return means the event is raised only when the price actually changes.

public event EventHandler<PriceChangedEventArgs>? PriceChanged;

The nullable annotation is honest: before anyone subscribes, the backing delegate is null. The event is public, but only Stock can invoke it. A subscriber can add or remove a handler and nothing more.

$ dotnet run
AAPL: 0.00 -> 189.50
AAPL: 189.50 -> 191.20

Subscribing and unsubscribing

The += operator adds a handler and -= removes it. An event holds a multicast delegate, so several handlers can be attached to the same event. They are called in the order in which they were added. Removing a handler that was never added does nothing and throws no exception.

Program.cs
var button = new Button("Save");

button.Clicked += (_, _) => Console.WriteLine("first handler");
button.Clicked += (_, _) => Console.WriteLine("second handler");

button.Press();

EventHandler second = (_, _) => Console.WriteLine("temporary handler");
button.Clicked += second;
button.Press();
button.Clicked -= second;
button.Press();

public sealed class Button
{
    public Button(string text) => Text = text;

    public string Text { get; }

    public event EventHandler? Clicked;

    public void Press()
    {
        Console.WriteLine($"pressing {Text}");
        Clicked?.Invoke(this, EventArgs.Empty);
    }
}

The button owns the Clicked event. The first press has two handlers, the second adds a temporary handler, and the third runs after it has been removed.

button.Clicked -= second;

Removing a handler needs the same delegate instance that was added. It is therefore a good habit to keep a named variable or method group for every subscription that has to be undone later. A lambda written twice creates two different delegates, even when the code looks identical, so the second one cannot remove the first.

$ dotnet run
pressing Save
first handler
second handler
pressing Save
first handler
second handler
temporary handler
pressing Save
first handler
second handler

Custom event accessors

A field-like event is convenient, but sometimes the add and remove accessors need to do more: update a counter, validate the subscriber, or forward the handler to another object. Writing the accessors explicitly replaces the compiler-generated backing delegate with one of your own.

Program.cs
var logger = new Logger();

EventHandler<string> console = (_, message) => Console.WriteLine($"console: {message}");
EventHandler<string> upper = (_, message) => Console.WriteLine($"upper: {message.ToUpperInvariant()}");

logger.Logged += console;
logger.Logged += upper;
Console.WriteLine($"subscribers: {logger.SubscriberCount}");

logger.Write("ready");

logger.Logged -= console;
Console.WriteLine($"subscribers: {logger.SubscriberCount}");

public sealed class Logger
{
    private EventHandler<string>? _logged;

    public event EventHandler<string> Logged
    {
        add
        {
            _logged += value;
            SubscriberCount++;
        }
        remove
        {
            _logged -= value;
            SubscriberCount--;
        }
    }

    public int SubscriberCount { get; private set; }

    public void Write(string message) => _logged?.Invoke(this, message);
}

The Logged event uses explicit accessors and keeps its own backing delegate in _logged. Each subscription and unsubscription updates SubscriberCount.

add
{
    _logged += value;
    SubscriberCount++;
}
remove
{
    _logged -= value;
    SubscriberCount--;
}

Inside an accessor, value is the handler being added or removed. The event itself has no automatic backing field in this form, so Write invokes _logged directly. The accessors are the only place where the count changes, which keeps the event and the counter consistent.

$ dotnet run
subscribers: 2
console: ready
upper: READY
subscribers: 1

Events in interfaces

An interface can declare an event, which forces every implementing type to expose it. The interface does not provide a backing delegate; each class implements the event in its own way. This is useful when callers should be able to subscribe without knowing the concrete type.

Program.cs
IConnection connection = new TcpConnection("db.local");
connection.Closed += (_, e) => Console.WriteLine($"closed: {e.Reason}");

connection.Close("idle timeout");

public interface IConnection
{
    event EventHandler<ClosedEventArgs>? Closed;

    void Close(string reason);
}

public sealed class ClosedEventArgs : EventArgs
{
    public ClosedEventArgs(string reason) => Reason = reason;

    public string Reason { get; }
}

public sealed class TcpConnection : IConnection
{
    public TcpConnection(string host) => Host = host;

    public string Host { get; }

    public event EventHandler<ClosedEventArgs>? Closed;

    public void Close(string reason)
    {
        Console.WriteLine($"closing {Host}");
        Closed?.Invoke(this, new ClosedEventArgs(reason));
    }
}

The caller works with IConnection and subscribes to its Closed event. The implementation raises the event after it starts closing the connection.

IConnection connection = new TcpConnection("db.local");
connection.Closed += (_, e) => Console.WriteLine($"closed: {e.Reason}");

The variable is typed as the interface, but the handler receives the concrete TcpConnection as the sender. If a class implements the event explicitly, the event is reachable only through the interface, just like an explicitly implemented method.

$ dotnet run
closing db.local
closed: idle timeout

Exceptions in event handlers

A multicast delegate invokes its handlers one after another. If one handler throws, the exception propagates immediately and the handlers that come after it are not called. The publisher does not catch the exception by default, so the caller of the method that raised the event sees it.

Program.cs
var publisher = new Publisher();

publisher.Changed += (_, _) => Console.WriteLine("first handler");
publisher.Changed += (_, _) => throw new InvalidOperationException("handler failed");
publisher.Changed += (_, _) => Console.WriteLine("third handler");

try
{
    publisher.Raise();
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"caught: {ex.Message}");
}

public sealed class Publisher
{
    public event EventHandler? Changed;

    public void Raise() => Changed?.Invoke(this, EventArgs.Empty);
}

The second handler throws. The first handler has already run, and the third never runs.

publisher.Changed += (_, _) => throw new InvalidOperationException("handler failed");

An exception-throwing expression lambda is enough to demonstrate the behavior. The catch surrounds the Raise call because that is where the delegate invocation happens. If subscribers must not be able to break the publisher, invoke each handler separately from GetInvocationList and catch exceptions per handler; that is a deliberate design choice, not the default.

$ dotnet run
first handler
caught: handler failed

Events and delegates

An event is not a separate kind of delegate; it is a delegate field with restricted access. Inside the declaring class, the event can be invoked, checked for null, and read. Outside, the compiler allows only += and -=. This is why replacing a public delegate field with an event is a breaking change for code that assigned or invoked the field, and why an event is the right choice for a public notification point.

Events are also the reason the EventHandler and EventHandler<T> delegates exist. A custom delegate type works too, but the built-in types give every subscriber the same (sender, args) shape and make the publisher easy to recognize. For callbacks that are not notifications, such as a method that takes a piece of work to run, an Action or Func parameter is usually simpler than an event.

Source

event keyword

Handle and raise events

EventHandler delegate

In this article we have declared, raised, and subscribed to C# events. See also the delegate, Action, lambda expression, and interface tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.