Reputation: 2242
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?
Upvotes: 68
Views: 27471
Reputation: 1340
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.
Upvotes: 0
Reputation: 244981
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.
Upvotes: 76