The difference between '+ = new EventHandler and' - = new EventHandler (anEvent)

I saw some code with - = new EventHandler (anEvent) , can you tell me what is different from '+ = new EventHandler ?

thanks

+2
source share
4 answers

One adds a delegate to the subscriber collection, and the other removes it.

For example, if you previously subscribed to an event, but you wanted the link to be deleted when, for example, you closed the form, you would use the -= version and you would not be notified anymore.

+12
source

The operator -= removes the even handler from the event, and += adds the event handler to the event.

For example:

 if (checkSomething()) { //handle clicks on myControl myControl.Click += MyEventHanderMethod; } else { //stop handling clicks on myControl myControl.Click -= MyEventHanderMethod; } 
+2
source

I think you should never use - = new EventHandler (anEvent), because the new event handler cannot yet be on the event delegate list. Need to do:

 EventHandler eventHandler = new EventHandler(anEvent); anObject.Event += eventHandler; ... anObject.Event -= eventHandler; 

Update

In fact, Ed is right, the delegate checks the target and method, not the handler object. It’s a little late for me to find out, it makes a lot of lines, I wrote outdated ...

+2
source

Both operators are just syntax shortcuts for the internal system methods System.MultiCastDelegate.Combine () and System.MultiCastDelegate.Remove (). Each delegate is derived from System.MultiCastDelegate, which contains an internal private linked list of delegates. New methods, which + = and - = are translated into the IL-compiler (Combine and Remove), effectively simply add (or remove, respectively) internal delegates from the delegate argument (on the right side + = or - +) to the internal delegate list on the left parties

+2
source

All Articles