Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wiring EventHandlers

Is there a difference between

Object.Event += new System.EventHandler(EventHandler);
Object.Event -= new System.EventHandler(EventHandler);

AND

Object.Event += EventHandler;
Object.Event -= EventHandler;

? If so, what?

Aren't they both just pointers to methods?

like image 587
Maxim Gershkovich Avatar asked May 27 '11 13:05

Maxim Gershkovich


People also ask

What is a event handler?

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.

What are event handlers example?

In general, an event handler has the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus. Many objects also have methods that emulate events. For example, button has a click method that emulates the button being clicked.

What is an event handler in Visual Basic?

An event handler is the code you write to respond to an event. An event handler in Visual Basic is a Sub procedure. However, you do not normally call it the same way as other Sub procedures. Instead, you identify the procedure as a handler for the event.


2 Answers

Both are Exactly same. But

Object.Event += EventHandler;
Object.Event -= EventHandler;

The above example compiles fine only in 3.0 or later version of C#, while if you are in 2.0 or before you can only use following construct.

Object.Event += new System.EventHandler(EventHandler);
Object.Event -= new System.EventHandler(EventHandler);

Look more about at Type inferencing. search for "Type Inference"

like image 93
crypted Avatar answered Sep 19 '22 12:09

crypted


No, they are exactly the same. The second version is purely a shorthand where the compiler creates an instance of the event handler for you. Just like simplified property syntax, using etc ... all compiler magic!

See this related question:

Difference between wiring events using "new EventHandler<T>" and not using new EventHandler<T>"?

like image 25
ColinE Avatar answered Sep 21 '22 12:09

ColinE