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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With