Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When adding an Event Handler, use 'new()' or not? [duplicate]

Possible Duplicate:
Attaching Eventhandler with New Handler vs Directly assigning it

What is the difference between assigning a callback to, lets say a button's Click event by using += new(...) versus just +=? Here are samples of each for clarity:

Button b = new Button();
b.Click += new System.EventHandler(button_Click);
b.Click += button_Click;

Does the first one create a new instance of the method button_Click whereas the second always uses the one defined in this?

like image 205
Jan Tacci Avatar asked Dec 12 '25 17:12

Jan Tacci


2 Answers

The second one is short hand for the first one, so both will create the event handler and add it to Click.

Here's a good explanation from the chapter on events in "C# in Depth."

like image 124
Ian Avatar answered Dec 14 '25 20:12

Ian


There is no difference.

You could also do..

b.Click += (e, sender) =>{
 // do something here
};

All three are the same, i.e. assigning a function to a delegate.

like image 22
Robin Maben Avatar answered Dec 14 '25 20:12

Robin Maben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!