Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

EventHandler<TEventArgs> — events with typed data

System.EventHandler<TEventArgs> defines a delegate for handling events that carry data of a specified type. It connects a publisher with subscribers without requiring a custom delegate type.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public delegate void EventHandler<in TEventArgs>(object? sender, TEventArgs e)
    where TEventArgs : allows ref struct;

System.EventHandler<TEventArgs> is a delegate type, not an event itself. It describes a handler returning void, with parameters object? sender (the event source, allowing null) and TEventArgs e (the data). The event keyword uses this type to declare an event; subscribers register handlers with += and remove them with -=.

In .NET 10, the declaration includes in TEventArgs and where TEventArgs : allows ref struct. The former enables contravariance for reference types; the latter also permits a ref struct type argument without requiring one. Inheriting from EventArgs is a convention, not a constraint of this API in .NET 10. Older signatures displayed in the documentation should not be treated as the declaration for this compilation target.

For conventional event data, create a class derived from EventArgs. When no additional data is needed, normally use the nongeneric EventHandler with EventArgs.Empty. A single delegate can represent multiple handlers.

In the example, Measured?.Invoke(this, ...) supplies the publisher and data, skipping invocation when there are no subscribers. After -=, the second measurement does not call OnMeasured, so the expected output is only Value: 21.

Examples

#nullable enable
using System;

var sensor = new Sensor();
sensor.Measured += OnMeasured;
sensor.Measure(21);
sensor.Measured -= OnMeasured;
sensor.Measure(22);

static void OnMeasured(object? sender, MeasurementEventArgs e)
{
    Console.WriteLine($"Value: {e.Value}");
}

sealed class MeasurementEventArgs : EventArgs
{
    public MeasurementEventArgs(int value) => Value = value;
    public int Value { get; }
}

sealed class Sensor
{
    public event EventHandler<MeasurementEventArgs>? Measured;

    public void Measure(int value)
    {
        Measured?.Invoke(this, new MeasurementEventArgs(value));
    }
}

Result

Value: 21

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources