In VS, Designer uses the first, but I saw the second also works. What are the differences? Is there any compelling reason to use the first and when could the second be better?
-
It is just syntax sugar. Tends to be important when you have write xxx.Click -= new EventHandler(foo); Create a *new* delegate to *remove* something??? C# newbies blow a gasket when they see that. – Hans Passant Dec 23 '14 at 15:49
-
I am a newbie too and yes it is counter-intuitive. I mean "foo" is a reference, as is new EventHandler(foo). So I can understand when adding it. But If I previously added something and I want to remove it, since we are talking about references, removing new EventHandler(foo) is not the same as removing foo, or even the previously added new EventHandler(foo)... What if I derive from EventHandler and then add new DerivedHandler(foo)? – Paralife Dec 23 '14 at 15:53
-
foo is not a reference, it is the name of a method. It doesn't turn into something you can reference until you create a delegate object that targets it. Which is why you have to create a new one. – Hans Passant Dec 23 '14 at 16:02
-
Oh, this was an aha moment... thanks. But wait, this means that in the first case the += assignment automatically creates a delegate for me? I mean compiler treats function names specially when they are right of a += statement when the left side is a delegate? So this is a kind of += overload? – Paralife Dec 23 '14 at 16:02
-
... I meant in the second case – Paralife Dec 23 '14 at 16:08
-
possible duplicate of [C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'](http://stackoverflow.com/questions/550703/c-difference-between-anevent-and-new-eventhandleranevent) – Paralife Dec 23 '14 at 16:16
1 Answers
Both snippets will produce the same code. The difference is that in the first case you are telling the compiler what delegate type you would like to use (i.e. EventHandler
), while in the second case you let the compiler figure out the type of the delegate from the context and the method group syntax.
There is no "better" or "worse" syntax in this specific case, because EventHandler
delegate is not likely to be renamed. As long as you stay consistent, and use the same syntax across your code base.
Generally, though, the second syntax lets you avoid multiple changes in code when you have to change the name of the delegate, without changing its signature. Since the compiler figures out the type implicitly, after renaming your delegate MyDelegate
to MyNewDelegate
you would not need to find all spots where you do new MyDelegate(myMethod)
and change it to new MyNewDelegate(myMethod)
.

- 714,442
- 84
- 1,110
- 1,523