Mark T
Mark T

Reputation: 3494

C# event removal syntax

I am confused by the syntax for removing event handlers in C#.

Something += new MyHandler(HandleSomething); // add
Something -= new MyHandler(HandleSomething); // remove

The "new" creates a new object on each line, so you add one object and then ask it to remove a different object.

What is really going on under the covers that this can work?
It sure isn't obvious from the syntax.

Upvotes: 8

Views: 1254

Answers (3)

Charles Bretana
Charles Bretana

Reputation: 146499

The += and the -= are syntax shortcuts for built-in internal methods named Add(), and Remove(), which add or remove a pointer to an internal linked list of delegates that the delegate has as a private field. When you run Remove, it starts at the head of the linked list and examines each delegate in the list one at a time until it finds one that is "equal" to the one you passed to the Remove() method. ( using -= syntax)

Then, it removes that one from the linked list, and patches the linked list to retain it's connectivity...

In this context, the 'equals' method (for a delegate()) is overridden so that it only compares the target of the delegate, and the methodPtr, which will be the same even though you have created a new delegate to pass to Remove...

Upvotes: 19

womp
womp

Reputation: 116977

The "new MyHandler" is actually redundant. You can simply do

Something += HandleSomething; // add
Something -= HandleSomething; // remove

All events in C# are multicast delegates, so the += and -= syntax indicates that you are adding/removing a delegate to the list of delegates that will be called.

As for what's going on behind the scenes, the best explanation that I've found is Jon Skeet's.

Upvotes: 7

Josh E
Josh E

Reputation: 7432

You can think of events as placeholder methods for the delegated logic that executes when the event is raised. A single event can have multiple subscribers (multi-casting), so the += and -= syntax is how a single event handler is attached or removed. Simply doing assignment would reset the event's subscriptions, which could cause unwanted side-effects.

EDIT: this link explains more about eventing in C#

Upvotes: -1

Related Questions