Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

System.EventHandler<TEventArgs> and System.EventArgs

Choose the delegate for an event with or without data, and learn how to remove a handler when it is no longer needed.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

// .NET 8 delegate signatures in namespace System (already provided by .NET):
public delegate void EventHandler<TEventArgs>(object? sender, TEventArgs e);
public delegate void EventHandler(object? sender, EventArgs e);

// In a publisher class, with using System; and a custom MessageEventArgs : EventArgs:
public event EventHandler<MessageEventArgs>? MessagePublished;
public event EventHandler? Flushed;

// Inside an instance method of that publisher:
MessagePublished?.Invoke(this, new MessageEventArgs("Build complete"));
Flushed?.Invoke(this, EventArgs.Empty);

System.EventHandler<TEventArgs> is the delegate type you use to declare an event that carries data. A handler returns void and receives object? sender, usually the object raising the event (it can be null), and TEventArgs e. System.EventArgs is a base class for event data, not a delegate. With C# 12 on .NET 8, the delegate does not require TEventArgs to inherit from EventArgs, but doing so is the standard .NET convention for custom event-data classes.

In a notification hub, declare MessagePublished with EventHandler<MessageEventArgs>. The class MessageEventArgs : EventArgs exposes a read-only Message property, so a handler can read e.Message without a cast. For Flushed, use the distinct non-generic type System.EventHandler: the second parameter is still EventArgs, and the publisher passes EventArgs.Empty, a shared instance with no extra data, rather than null.

Outside code subscribes with += and unsubscribes with -=, but cannot raise the event directly. The declaring class raises it with ?.Invoke(this, e), which skips invocation when there are no subscribers. An ordinary delegate invocation runs synchronously. If a handler throws an uncaught exception, it propagates to the caller and later handlers in the invocation list are skipped.

Use the same method to subscribe and unsubscribe; for a lambda, keep the delegate you subscribed with. Unsubscribe when you no longer need the notifications, especially if the publisher outlives the subscriber: the publisher's delegate can keep the subscriber object alive.

Examples

#nullable enable
using System;

var hub = new NotificationHub();
hub.MessagePublished += OnMessagePublished;
hub.Flushed += OnFlushed;

hub.Publish("Build complete");
hub.Flush();

hub.MessagePublished -= OnMessagePublished;
hub.Flushed -= OnFlushed;

hub.Publish("Not printed");
hub.Flush();

static void OnMessagePublished(object? sender, MessageEventArgs e)
    => Console.WriteLine(e.Message);

static void OnFlushed(object? sender, EventArgs e)
    => Console.WriteLine("Flushed");

sealed class MessageEventArgs : EventArgs
{
    public MessageEventArgs(string message) => Message = message;

    public string Message { get; }
}

sealed class NotificationHub
{
    public event EventHandler<MessageEventArgs>? MessagePublished;
    public event EventHandler? Flushed;

    public void Publish(string message)
        => MessagePublished?.Invoke(this, new MessageEventArgs(message));

    public void Flush()
        => Flushed?.Invoke(this, EventArgs.Empty);
}

Result

Build complete
Flushed

`NotificationHub` exposes two independent events. The first calls to `Publish` and `Flush` print `Build complete` and `Flushed`, respectively. After both handlers are removed, the next calls print nothing.

Related lessons

  • C# · Lesson 23 · Intermediate · Version: 2
  • C# · Lesson 24 · Intermediate · Version: 2
  • C# · Lesson 25 · Intermediate · Version: 2

Sources