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?
EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event. Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx.
The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.
An event is declared using the event keyword. Delegate is a function pointer. It holds the reference of one or more methods at runtime. Delegate is independent and not dependent on events.
An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With