Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ‘ += new EventHandler’ and ‘ -= new EventHandler(anEvent)’

Tags:

c#

I saw some code using -= new EventHandler(anEvent) , can you one tell me what is the different to ‘ += new EventHandler’ ?

Thanks


2 Answers

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.

like image 167
Ed S. Avatar answered Jun 21 '26 06:06

Ed S.


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;
}
like image 35
nikmd23 Avatar answered Jun 21 '26 06:06

nikmd23



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!