Home » c# » Custom EventHandler vs. EventHandler<EventArgs>

Custom EventHandler vs. EventHandler<EventArgs>

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

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.