11

What is the actual difference, advantages and disadvantages, of creating a new event handler, vs assigning it directly to the event?

_gMonitor.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged);

vs

_gMonitor.CollectionChanged += OnCollectionChanged;
John Saunders
  • 160,644
  • 26
  • 247
  • 397
HaxElit
  • 3,983
  • 7
  • 34
  • 43
  • possible duplicate of [C#: Difference between ' += anEvent' and ' += new EventHandler(anEvent)'](http://stackoverflow.com/questions/550703/c-difference-between-anevent-and-new-eventhandleranevent) – nawfal Jul 06 '14 at 20:18

2 Answers2

12

In C# 2.0 and above, they are identical. In C# 1.2 (the one that shipped with .NET 1.1), only the first syntax (with new) compiles ;-p

The second syntax saves key presses, but VS intellisense will typically suggest the first. Ultimately, it makes very little difference. I generally use the second syntax in code-samples online, simply because it avoids going over the (narrow) column width!

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I think the first one creates memory leak issues, but I cannot find anything to prove this. But I have faced such issues in past the windows service was not closing just because the `timer.Tick += new Handler_Tick(timer_TickMethod);` was not `timer.Tick += timer_TickMethod;` and unsubscribing was not helpful thus with `timer.Tick += new Handler_Tick(timer_TickMethod);`. – Harsh Baid Aug 31 '12 at 09:01
  • 1
    @HarshBaid you are incorrect; they compile to ***exactly*** the same thing. For info, delegate unsubscription is based on a match on the MethodInfo and *instance*; it doesn't need to be the same actual delegate instance to correctly unsubscribe – Marc Gravell Aug 31 '12 at 09:02
  • how about `_gMonitor.CollectionChanged -= OnCollectionChanged` or `_gMonitor.CollectionChanged += new NotifyCollectionChangedEventHandler(OnCollectionChanged)`, will it work with the first option? – Louis Rhys Aug 31 '12 at 09:12
  • @mark hm I think you are right, I would have mixed it with unsubscribe event handler. :P – Harsh Baid Aug 31 '12 at 09:23
  • @LouisRhys again, other than "one is a subscribe, one is an unsubscribe", they are identical – Marc Gravell Aug 31 '12 at 09:43
4

The compiler has enough information available to make the new EventHandler effectively syntactic sugar.

It knows that you are attaching an event handler to an event, as only += and -= are valid at this point, so you don't need tell it what to do.

ChrisF
  • 134,786
  • 31
  • 255
  • 325