Skip to content

Support for generic sender parameter in EventHandler #28289

@simplexidev

Description

@simplexidev

When using event handlers EventHandler and EventHandler<TEventArgs>, it is not possible to pass a generic sender to the delegate without writing your own delegate type. There should be a event handler that has a second generic parameter to specify the type of sender.

Rationale/Usage

This is a nice-to-have that would reduce the number of custom event handers (that take just a sender and args) by exposing a new delegate, such as EventHandler<TSender, TEventArgs>.

For example, say I had a class with an event that was specific to it and it's derivatives:

public delegate void LoadingEventHandler(FooObject sender, EventArgs e);

public class FooObject
{
    public FooObject()
    {
        Loading.Invoke(this, EventArgs.Empty);
    }
    public event LoadingEventHandler Loading;
}

With a EventHandler<TSender, TEventArgs> delegate, the above could turn into:

public class FooObject
{
    public FooObject()
    {
        Loading.Invoke(this, EventArgs.Empty);
    }
    public event EventHandler<FooObject, EventArgs> Loading;
}

Proposed API

namespace System
{
    /// <summary>
    /// Represents the method that will handle an event when the event provides data.
    /// </summary>
    /// <typeparam name="TSender">The type of sender object.</typeparam>
    /// <typeparam name="TEventArgs">The type of the event data generated by the event.</typeparam>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">An object that contains the event data.</param>
    public delegate void EventHandler<TSender, TEventArgs>(TSender sender, TEventArgs e)
        where TSender : object;
}

Updates

  • Updated this issue to follow the API review process/other guidelines.
  • Updated the Proposed API with type parameters.
  • Updated the Proposed API: Removed type parameter constraints to align with the existing EventHandler implementations, as TEventArgs does not have to be of type EventArgs. The type constraint for TSender remains as object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Runtimein-prThere is an active PR which will close this issue when it is mergedpartner-impactThis issue impacts a partner who needs to be kept updated

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions