views:

147

answers:

4

When must we use this operator by events? What is its usage?

+1  A: 

You remove the Eventhandler Function. C# Tutorial, Events and Delegates

Aurril
+10  A: 

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.

Jon Skeet
+1. It's also worth mentioning that failing to unsubscribe to an event is often the cause of a program running out of memory, as it prevents objects becoming eligible for GC.
RichardOD
Jon, I'm a little frightened by the fact we both started our answers with "Just as..." ;-)
T.J. Crowder
+3  A: 

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 -=).

T.J. Crowder
+3  A: 

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.

Dan Tao