6

I just realized I can add an event handler in two ways:

Consider an event handler like so:

private void MyEventHandler()
{}

Method 1: Instantiate a new delegate

MyObject.MyEvent += new Action(MyEventHandler);

Method 2: Add event handler without instantiating a new delegate

MyObject.MyEvent += MyEventHandler;

Is there any difference in between these two implementations that should be considered?

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Verax
  • 2,409
  • 5
  • 27
  • 42
  • Great, two completely opposite answers. Now I'm curious. – R. Martinho Fernandes Jan 13 '11 at 03:07
  • 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:15

2 Answers2

6

There is no difference, the generated IL is the same. The shorter form was introduced in .net/c# 2.0 as a convenience function, although Visual Studio still does the first form on Tab Completion.

See this question for some more info.

Community
  • 1
  • 1
Michael Stum
  • 177,530
  • 117
  • 400
  • 535
2

I believe that while you can unsubscribe from the second, you'd not be able to unsubscribe from the first.

That would be a pretty important distinction. There is really nothing to be gained by wrapping it in an Action in any case.

update

Okay, I think I misunderstood what you were doing. If the event is declared as

public event Action MyEvent;

then the two subscriptions are equivalent, the second being shorthand for the first.

There are actually other ways to add event handlers:

MyObject.MyEvent += delegate { MyEventHandler(); };

MyObject.MyEvent += () => MyEventHandler();

In these cases, you would not be able to unsubscribe. In these examples, the delegates are calling the handler method, but usually when employing this method it is to avoid having to create separate handler methods -- the handler code goes right in the anonymous method.

Community
  • 1
  • 1
Jay
  • 56,361
  • 10
  • 99
  • 123
  • 1
    This is consistent with my observations too. In order to unsubscribe using the first syntax, you have to store the instance of the delegate in a variable before attaching it, then reference that variable when you unsubscribe. I've never understood why VS continues to use the wrapping syntax when it prevents the removal of the event handler... – Bradley Smith Jan 13 '11 at 03:15
  • 1
    @Bradley: It doesn't prevent removal. `MulticastDelegate` implements Equals so this is always true: `new EventHandler(Handler) == new EventHandler(Handler)`. – Rick Sladkey Jan 13 '11 at 03:52