Search code examples
c#.neteventsanonymous-methods

How do I deregister an anonymous handler?


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?


Solution

  • 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.