Possible Duplicate:
C#: How to remove a lambda event handler
Is it possible to remove an event handler which was attached as anonymous function? Let's say I have an event, and I subscribe to it in this way:
TestClass classs = new TestClass ();
classs.myCustomEvent += (a,b) => { Console.Write(""); };
Is it possible somehow to remove this eventHandler using -= ??
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.
This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job.
Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.
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.
It is possible, but you need to store it in a local variable first:
MyDelegate handler = (a, b) => { Console.Write(""); };
class.myCustomEvent += handler;
class.myCustomEvent -= handler;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With