When must we use this operator by events? What is its usage?
You remove the Eventhandler Function. C# Tutorial, Events and Delegates
Just as += subscribes you a handler to the event, -= unsubscribes it.
Use it when you no longer want a particular handler to be called when the event is raised. You often only need to use it the component raising the event is logically longer lived than the handler of the event - if you don't unsubscribe, the "event raiser" effectively has a reference to the handler, so can keep it alive longer than you want.
Just as you can add event handlers via +=
, you can remove them via -=
.
For instance:
mybutton.Click += new EventHandler(myhandler);
You can later remove it like this:
mybutton.Click -= new EventHandler(myhandler);
...because event handlers for the same method and instance are equivalent (so you don't need to retain a reference to the handler you used with +=
and use that one with -=
).
The +=
and -=
operators can be used in C# to add/remove event handlers to/from one of an object's events:
// adds myMethod as an event handler to the myButton.Click event
myButton.Click += myMethod;
After the above code runs, the myMethod
method will be called every time myButton
is clicked.
// removes the handler
myButton.Click -= myMethod;
After the above code runs, clicking on myButton
will no longer cause myMethod
to be called.