5

I have the following code attaching event handler:

this.btnOK.Click += (s,e) => { MessageBox.Show("test");  };

Can I unsubscribe that lambda expression from the vent?

Hamlet Hakobyan
  • 32,360
  • 6
  • 50
  • 66
v.chjen
  • 575
  • 1
  • 7
  • 19
  • You can't unsubscribe anonymous function because it is anonymous and you can't access it. Possible solution you can find on http://stackoverflow.com/questions/9745280/how-to-unsubscribe-an-anonymous-function-in-dispose-method-of-a-class. You cant unsubscribe anonoy – Jozef Cechovsky May 06 '14 at 05:42

3 Answers3

6

Why don't just save the assigned lambda?

 EventHandler lambda = (s,e) => { MessageBox.Show("test");  };

 ...

 this.btnOK.Click += lambda;

 ... 

 this.btnOK.Click -= lambda;
Romano Zumbé
  • 7,735
  • 4
  • 32
  • 52
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
-2

You cannot un-assign that event because it is a anonymous method.

Give it a name and you are ready to unsubscribe.

-3

you can do :

this.btnOK.Click = null;
Adrián Romero
  • 600
  • 6
  • 17