6

I have a list of Button, and I add an event handler for each button:

List<Button> buttons = new List<Button>();

for (int i = 0; i < 10; i++)
{
   Button btn = new Button();
   btn.Click = new RoutedEventHandler(OnbtnClick);
   buttons.Add(btn);
}

Then I clear the list:

/* Have I to remove all events here (before cleaning the list), or not?
foreach (Button btn in buttons)
   btn.Click -= new RoutedEventHandler(OnbtnClick);
*/

buttons.Clear();
Nick
  • 10,309
  • 21
  • 97
  • 201
  • I could be wrong, but I don't believe btn.Click -= new RoutedEventHandler(OnbtnClick); even removes the handler, since you are using the new operator instead of the original added handler. – Kevin DiTraglia Jun 13 '12 at 18:27
  • 2
    @KDiTraglia It's a valid syntax, see [this](http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx) tutorial. – gliderkite Jun 13 '12 at 18:32
  • @gliderkite ah my mistake, I thought I remember reading somewhere that it didn't work. – Kevin DiTraglia Jun 13 '12 at 18:33
  • @KDiTraglia unsubscribing with a lambda doesn't work, btn.Click -= (x,y) => SomeMethod. Maybe that's what you're thinking of? – RichK Jun 13 '12 at 21:54

2 Answers2

6

When you clear the list you clear all references to the handlers along with them. Once your handlers leave scope (which is to say when the function finally exits and no objects have references to the created handlers), the Garbage Collector will get around to removing all related memory (on its own schedule of course).

So no, you don't need to manually delete the handlers.

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
1

check this solution : How to remove all event handlers from a control

this is what u after it.hope this help.

Community
  • 1
  • 1
Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63