Possible Duplicate:
How to correctly unregister an event handler
MSDN states the following two event subscriptions are exactly equivalent (C# 2.0 vs 1.0 syntax):
publisher.CustomEvent += HandleCustomEvent;
publisher.CustomEvent += new CustomEventHandler(HandleCustomEvent);
I note that the newer syntax hides instantiation of a delegate object.
Do I need to keep a reference to a delegate so that I can properly unsubscribe later?
// Retain reference to delegate used to subscribe.
this.handleCustomEvent = new CustomEventHandler(HandleCustomEvent);
publisher.CustomEvent += this.handleCustomEvent;
...
// Use earlier reference to unsubscribe.
publisher.CustomEvent -= this.handleCustomEvent;
Or, is this the same thing?
publisher.CustomEvent += HandleCustomEvent;
...
publisher.CustomEvent -= HandleCustomEvent;
If they are the same, why?
Does -= HandleCustomEvent also create a new()? If so, isn’t this object different than the object created by += HandleCustomEvent?
This is the exact same thing I think, you just focused on the second, short-hand syntax bit.
How to correctly unregister an event handler
I wouldn’t answer on that just, but I wanted to add this…
if you’d like you might want to take a look at Rx – Reactive Extensions which frees you of these very problems. Unsubscribe is basically not mandatory unless you would want to ‘stop’ the event sooner (this is simplified, there are more details to this)