Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit to explicit use of "new EventHandler" declaration?

Tags:

c#

.net

In assigning event handlers to something like a context MenuItem, for instance, there are two acceptable syntaxes:

MenuItem item = new MenuItem("Open Image", btnOpenImage_Click);

...and...

MenuItem item = new MenuItem("Open Image", new EventHandler(btnOpenImage_Click));

I also note that the same appears to apply to this:

listView.ItemClick += listView_ItemClick;

...and...

listView.ItemClick += new ItemClickEventHandler(listView_ItemClick);

Is there any particular advantage for the second (explicit) over the first? Or is this more of a stylistic question?

like image 972
DonBoitnott Avatar asked Jul 03 '13 12:07

DonBoitnott


People also ask

What is the purpose of an EventHandler?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.

Why is EventHandler t a useful generic type?

The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. You simply provide the type of the event data object as the generic parameter.

Can EventHandler return a value?

A second way for an event handler method to return a value back to the sender is for the delegate that the event is based on to include just that -- a return value. Instead of being declared to return void, the delegate on which the event is based can be defined to return a type such as bool or int.

What is the difference between event and EventHandler?

The event is the thing that RAISES an event, to which something will subscribe. The EventHandler is the thing that HANDLES an event - i.e. it specifies the method that is used to subscribe to the event.


1 Answers

In C# 1.0 you had no choice but to explicitly define the delegate type and the target.

Since C# 2.0 the compiler allows you to express yourself in a more succinct manner by means of an implicit conversion from a method group to a compatible delegate type. It's really just syntactic sugar.

Sometimes you have no choice but to use the long-winded syntax if the correct overload cannot be resolved from the method group due to an ambiguity.

like image 175
User 12345678 Avatar answered Sep 20 '22 21:09

User 12345678