Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the removing an event handler with -= work when a "new" event is specified

In the MSDN Events Tutorial hooking up to events is demonstrated with the example:

// Add "ListChanged" to the Changed event on "List":
List.Changed += new ChangedEventHandler(ListChanged);
...
// Detach the event and delete the list:
List.Changed -= new ChangedEventHandler(ListChanged);

Where as I have been keeping a reference to the delegate. Example:

ChangedEventHandler myChangedEvent = new ChangedEventHandler(ListChanged);
List.Changed += myChangedEvent;
...
List.Changed -= myChangedEvent;

When I look at the MSDN example code, "-= new" just looks wrong to me. Why would this List have a reference to an event handler I just created?

Obviously I must be thinking about things the wrong way? Can I get a pointer to a technical explanation of how -= works, seeing how -= appears to not be using one.

like image 519
jphofmann Avatar asked Oct 24 '11 21:10

jphofmann


2 Answers

Yes, this is confuzzling syntax. A delegate object must be created before the handler can be removed from the event. Which is why C# supports this syntax as well:

 List.Changed -= ListChanged;

which looks more logical. The compiler however still generates the exact same code. Under the hood, the MulticastDelegate.RemoveImpl() method iterates the invocation list and removes delegate objects from that list whose Target and Method properties match.

like image 147
Hans Passant Avatar answered Sep 30 '22 15:09

Hans Passant


Event unsubscribing uses value equality, not reference equality. So the newly created delegate matches the old one(both target object and method are the same) and thus removes the old delegate from the invocation list.

like image 26
CodesInChaos Avatar answered Sep 30 '22 14:09

CodesInChaos