Custom EventHandler vs. EventHandler<EventArgs>

haiyyu picture haiyyu · Dec 29, 2011 · Viewed 24.8k times · Source

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?

Answer

Cody Gray picture Cody Gray · Dec 29, 2011

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.