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?
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.
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.
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.
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"
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>"?
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