What does this mean in C #: using - = event statement?

When should we use this operator with events? What is its use?

+6
operators c # events
source share
5 answers

Just as + = the event handler signs you, - = unsubscribes it.

Use it when you no longer want a handler to be called when an event is raised. You often only need to use it, the component raising the event is logically more durable than the event handler. If you do not unsubscribe, the "event collector" has a link to the handler, so it can support it longer than you want.

As noted in the comments:

  • -= only one handler will be deleted; if there are several handlers signed (even using the same delegate), it will only reduce the number of handlers by 1. The last instance of the specified handler is the one that was deleted. (So, if you previously had handlers A, B, A, C signed in this order, and deleted A, you would end up in A, B, C.)
  • -= does not cause an error if the specified handler is not already subscribed to the delegate; it just ignores the request. This is true even if there are currently no handlers subscribing to it.
+12
source share

Just as you can add event handlers via += , you can remove them with -= .

For example:

 mybutton.Click += new EventHandler(myhandler); 

You can remove it as follows:

 mybutton.Click -= new EventHandler(myhandler); 

... because event handlers for the same method and instance are equivalent (so you don’t need to keep a reference to the handler that you used with += and use it with -= ).

+6
source share

The += and -= operators can be used in C # to add / remove event handlers to / from one of the object's events:

 // adds myMethod as an event handler to the myButton.Click event myButton.Click += myMethod; 

After the above code is myMethod method will be called every time myButton pressed.

 // removes the handler myButton.Click -= myMethod; 

After executing the above code, clicking on myButton will no longer call myMethod .

+3
source share

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

+1
source share

I suspect that the background logic + = is to add a handler to the list / array of event handlers for this event. When - = is used, it compares your right-hand argument with the list of event handlers that it holds for that event, and removes it from the list. If you do a few + = for this event, each handler will be called.

It is indicated differently: + = means adding a method to the list of calling methods when an event occurs. - = means removing the specified method from the list of methods to call.

If everything is deleted, the event will not have handlers, and the event will be ignored.

+1
source share

All Articles