views:

310

answers:

2

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?

+8  A: 

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.

driis
Hah, so this was asked before. I used the term "deregister" instead of "unsubscribe" so it didn't come up.
Bogdan Gavril
+2  A: 

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
it needn't be a class member, it can be a within the same method
Bogdan Gavril