I saw some code using -= new EventHandler(anEvent) , can you one tell me what is the different to ‘ += new EventHandler’ ?
Thanks
I saw some code using -= new EventHandler(anEvent) , can you one tell me what is the different to ‘ += new EventHandler’ ?
Thanks
One adds a delegate to the collection of subscribers, the other removes it.
For example, if you had previously subscribed to an event, but you wanted the reference removed when you, say, closed a form, you would use the -=
version and you would no longer be notified.
The -=
operator removes an even handler from an event, while +=
adds an event handler to an event.
For example:
if (checkSomething())
{
//handle clicks on myControl
myControl.Click += MyEventHanderMethod;
}
else
{
//stop handling clicks on myControl
myControl.Click -= MyEventHanderMethod;
}
I guess one should never use -= new EventHandler(anEvent) because the new event handler cannot yet in the event delegates list. One should do:
EventHandler eventHandler = new EventHandler(anEvent);
anObject.Event += eventHandler;
...
anObject.Event -= eventHandler;
Updated
Actually Ed is right, the delegate will check the target and method, not the handler object. Kinda a late for me to learn this, makes a lot of line I wrote obsolete...
Both operators are simply syntactical shortcuts for the internal framework methods System.MultiCastDelegate.Combine() and System.MultiCastDelegate.Remove(). Every delegate derives from System.MultiCastDelegate, which contains an internal private linked list of delegates. The new methods that += and -= are translated into by the IL compiler (Combine and Remove) effectively just add, (or remove, respectively) the internal delegates from the delegate argument (on the right hand side of the += or -+) to the internal link list of delegates on the left hand side,