Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom EventHandler vs. EventHandler<EventArgs>

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?

like image 739
haiyyu Avatar asked Dec 29 '11 12:12

haiyyu


People also ask

What does EventArgs mean?

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.

Is an EventHandler a delegate?

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.

What is difference between event and delegate in C#?

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.

What is C# EventHandler?

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.


1 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.

like image 145
Cody Gray Avatar answered Sep 22 '22 13:09

Cody Gray