Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing anonymous event handlers [duplicate]

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 -= ??

like image 658
magneto Avatar asked Jun 23 '11 20:06

magneto


People also ask

How do I delete an 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?

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job.

How do you clean up event listeners?

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.

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

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;
like image 117
fparadis2 Avatar answered Oct 23 '22 08:10

fparadis2