Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding and Removing Anonymous Event Handler

I was wondering if this actually worked ?

private void RegisterKeyChanged(T item)  {     item.OnKeyChanged += (o, k) => ChangeItemKey((T)o, k); }  private void UnRegisterKeyChanged(T item)  {     item.OnKeyChanged -= (o, k) => ChangeItemKey((T)o, k); } 

How does the compiler know that the event handlers are the same ? Is this even recommended?

like image 813
HaxElit Avatar asked Jan 12 '10 18:01

HaxElit


People also ask

How do I get rid of anonymous event handler?

There is no way to cleanly remove an event handler unless you stored a reference to the event handler at creation. I will generally add these to the main object on that page, then you can iterate and cleanly dispose of them when done with that object.

Can you remove event listener with anonymous function?

To call removeEventListener with an anonymous function with JavaScript, we assign the anonymous event listener function to a variable and call addEventListener and removeEventListener with the variable.

Why do we use anonymous event handlers in Windows Forms?

Anonymous methods are a simplified way for you to assign handlers to events. They take less effort than delegates and are closer to the event they are associated with. You have the choice of either declaring the anonymous method with no parameters or you can declare the parameters if you need them.


1 Answers

There's an MSDN page that talks about this:

How to Subscribe to and Unsubscribe from Events

Note in particular:

If you will not have to unsubscribe to [sic] an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.

And also:

It is important to notice that you cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, it is necessary to go back to the code where you subscribe to the event, store the anonymous method in a delegate variable, and then add the delegate to the event . In general, we recommend that you do not use anonymous functions to subscribe to events if you will have to unsubscribe from the event at some later point in your code.

like image 50
Ryan Lundy Avatar answered Oct 06 '22 15:10

Ryan Lundy