Runtime: Support for generic sender parameter in EventHandler

Created on 30 Dec 2018  Â·  7Comments  Â·  Source: dotnet/runtime

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 : class
        where TEventArgs : EventArgs;
}

Updates

  • Updated this issue to follow the API review process/other guidelines.
  • Updated the Proposed API with type parameters.
api-suggestion area-System.Runtime

Most helpful comment

Any updates on the issue?

All 7 comments

This would cause a huge change in the framework because you can't do optional generics (to my knowledge). Could break a lot of things.

@utkumaden I'm not sure it would break anything, as you would have to specify TSender as well as TEventArgs. I don't think this addition would have any effect on existing types using EventHandler or EventHandler<TEventArgs>.

@tom-corwin, now that you put it that way it makes more sense.

@jeffschwMSFT @KKhurin

winrt has TypedEventHandler for this… it's not present in .NET. Maybe it could be added which would also make things more consistent?

Any updates on the issue?

Whether we bring overTypedEventHandler or have a new delegate for EventHandler, I would be happy with it. Are there any further updates on this issue?

Was this page helpful?
0 / 5 - 0 ratings