views:

132

answers:

4

Hi

Can you tell me what the difference is between these methods of attaching an event handler?

//Method 1
this.button4.Click += new RoutedEventHandler(button4_Click);

//Method 2
this.button4.Click += button4_Click;

...

void button4_Click(object sender, RoutedEventArgs e) { }
+1  A: 

No difference whatsoever - the second is just syntactic shugar added in C# 2.0. And in C# 3.0 lambdas are even more concise.

Anton Gogolev
+3  A: 

As Anton says, there's no difference.

Just as a bit more background, this isn't specific to events. That's just one use of the feature in C# 2.0, which is implicit conversion of method groups to delegates. So you can similarly use it like this:

EventHandler handler = button4_click;

Another change to delegates in C# 2.0 is that they're now variant - this means that (for example) you can use a method declared with the EventHander signature as a MouseEventHandler:

MouseEventHandler handler = button4_click;

Then of course there's anonymous methods, but that's a whole different ballgame :)

Jon Skeet
+1  A: 

It is indeed syntactic sugar (it compiles to identical CIL)

The benefit to the first approach is that it is explict at the call site what event type you are using.

The benefit to the second is that, should the delegate type change but stay compatible the code will not require changing, if it changes but is incompatible you need only fix the method, not the places it is attached to the event.

As ever this is a balance as to which pro/con is more use to the situation at hand

ShuggyCoUk
A: 

thanks...

your answers are very complete.