What is the difference between "Action<object?, EventArgs>" and "EventHandler(object? sender, EventArgs e)"?

48 views Asked by At
public delegate void Action<object?, EventArgs>(object? sender, EventArgs e);

public delegate void EventHandler(object? sender, EventArgs e);

What is the difference between those two lines? They seem to be functionally equal.

2

There are 2 answers

4
PMF On BEST ANSWER

Rotabor's answer is basically correct, except for the reasoning: EventHandler exists since .NET Framework 1.1, which did not have generics and thus also did not yet have Action<T>. Only fully defined delegate types where allowed.

When Action (with it's generic overloads) was added in .NET Framework 2.0, EventHandler was kept for backwards compatibility.

0
rotabor On

If fact, there is no difference:

EventHandler a;
Action<object?, EventArgs> b;

void c(object? o, EventArgs e) { }

void d() {
    a = c; b = c; // no error
}

"EventHandler" is introduced just for convenience to use anywhere for event-related code.