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,965
  • 6
  • 52
  • 68
v.chjen
  • 615
  • 1
  • 8
  • 20
  • 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 – y0j0 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,893
  • 4
  • 33
  • 55
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
-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
  • 620
  • 7
  • 17