Custom EventHandler vs. EventHandler<EventArgs>

C#EventsHandlers

C# Problem Overview


Recently I've been wondering if there is any significant difference between this code:

public event EventHandler<MyEventArgs> SomeEvent;

And this one:

public delegate void MyEventHandler(object sender, MyEventArgs e);
public event MyEventHandler SomeEvent;

They both do the same thing and I haven't been able to tell any difference. Although I've noticed that most classes of the .NET Framework use a custom event handler delegate for their events. Is there a specific reason for this?

C# Solutions


Solution 1 - C#

You're right; they do the same thing. Thus, you should probably prefer the former over the latter because it's clearer and requires less typing.

The reason that lots of the .NET Framework classes have their own custom event handler delegates is because they were written before generics (which allowed the shorthand syntax) were introduced in version 2.0. For example, almost all of the WinForms libraries were written before generics, and back in those days, the latter form was the only way of doing things.

Solution 2 - C#

The second way gives more flexibility and type safety. There are less methods with corresponding signature => less place for a mistake. Custom delegate allows to specify exactly parameters you need (or specify no one) - no sender+args cargo cult.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhaiyyuView Question on Stackoverflow
Solution 1 - C#Cody GrayView Answer on Stackoverflow
Solution 2 - C#SerGView Answer on Stackoverflow