4

C# 2.0 has a neat feature called anonymous functions. This is intended to be used mostly with events:

Button.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };

Now, suppose that Button is a static member, then adding delegates to it would count as unmanaged resources. Normally, I would have to deregister the handler before regestring it again. This is a pretty common use case for GUI programming.

What are the guidelines with anonymous functions? Does the framework deregrister it automatically? If so, when?

Bogdan Gavril MSFT
  • 20,615
  • 10
  • 53
  • 74

2 Answers2

9

No, anonymous functions will not get deregistered automatically. You should make sure to do it yourself, if the event should not be hooked up for the whole lifetime of your application.

To do this, of course, you would have to store the delegate reference, to be able to de-register it. Something like:

EventHandler handler = delegate(System.Object o, System.EventArgs e)
               { System.Windows.Forms.MessageBox.Show("Click!"); };
Button.Click += handler;
// ... program code

Button.Click -= handler;

Also, see this question.

Community
  • 1
  • 1
driis
  • 161,458
  • 45
  • 265
  • 341
2

If I recall correctly (and I can recall where I read this) inline anonymous delegates cannot be removed.

You would need to assign to a (static) delegate field.

private static EventHandler<EventArgs> myHandler = (a,b) => { ... }

myButton.Click += myhandler;
...
myButton.Click -= myHandler;
Richard
  • 106,783
  • 21
  • 203
  • 265