views:

277

answers:

4

I've always assigned event handlers like this, guided by Intellisense auto-completion.

RangeSelector.RangeChanged += new EventHandler(RangeSelector_RangeChanged);

I've recently noticed one of my colleagues does it this way.

RangeSelector.RangeChanged += RangeSelector_RangeChanged;

Both methods are syntactically correct, compile and behave as expected.

What are the differences, benefits or disadvantages of these methods. Do they result in the same IL code or is there some subtle difference that I need to be aware of?

+2  A: 

No difference, it results in the same IL.

It's just a way to say the same thing with less code.

Nifle
+9  A: 

What are the differences, benefits or disadvantages of these methods.

The second method is newer, i.e. it is only supported since C# 2.0 (I believe), which added an automatic conversion from a method group (i.e. a method name) to a delegate. The constructor call is thus added by the compiler and the second method is just syntactic sugar for the first one.

Because of that, there are no other differences between the two.

Since the second method does the same as the first, with less syntax, it should be preferred.

Konrad Rudolph
Also, if you change the event signature, you only need to change code in two places, the event declaration, and the handler itself, but not wherever you assign/deassign the handler.
Matthew Scharley
+1, However as to "should be prefered" thats questionable. If typing += followed by hitting the tab button twice generated the newer syntax I'd agree. Currently the quickest way to add an event handler is to generate the older syntax with the IDEs help.
AnthonyWJones
@Matthew Scharley: if you use Visual Studio's built-in refactoring support you won't have to worry about such things.
Ian Kemp
I'd love the autocompletion to generate the second form...
Thomas Levesque
@Anthony: I’m a compulsive perfectionist, I use auto-completion, then go back to edit the sh*t it produced manually. Visual clutter in code is **teh enemy**.
Konrad Rudolph
Thanks guys. I think I'll start using the second form then.
Steve Crane
+2  A: 

The result is the same in both cases. But in the latter the C# compiler will infer the EventHandler type from the code, thus saving you a few key strokes.

Peter Lillevold
+1  A: 

yes, compiler creates the same IL code in both cases, the second case is just syntax sugar

ArsenMkrt