Take the 2-minute tour ×

I was wondering if setting an object to null will clean up any eventhandlers that are attached to the objects events...


Button button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;

button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;


Will this cause a memory leak?

share|improve this question

3 Answers 3

up vote 15 down vote accepted

If there are no other references to button anywhere, then there is no need to remove the event handler here to avoid a memory leak. Event handlers are one-way references, so removing them is only needed when the object with events is long-lived, and you want to avoid the handlers (i.e. objects with handler methods) from living longer than they should. In your example, this isn't the case.

share|improve this answer
Does this mean event handlers for application bars doesnt need explicit removing aswell (statechanged for example)? –  Hans Petter Naumann Jul 31 '12 at 13:30
This is a reverse situation. AppBar is a long-lived object, and an event handler would, at the minimum, keep the object the delegates refers to alive for as long as AppBar is alive, and you might not want that to happen. On the other hand, if the handler is a method on the window that owns the bar, it doesn't matter. –  Pavel Minaev Aug 1 '12 at 20:29

See the discussion here under "The final question: do we have to remove event handlers?"


share|improve this answer

Summary: You need to explicitly unsubscribe when the event source/publisher is long-lived and the subscribers are not. If the event source out-lives the subscribers, all registered subscribers are kept "alive" by the event source (not collected by the GC) unless they unsubscribe (and remove the reference to themselves from the event publisher's notification list)

Also this is a duplicate of http://stackoverflow.com/questions/506092/is-it-necessary-to-explicitly-remove-event-handlers-in-c and has a good title n answer. So voting to close.

share|improve this answer
I saw that Q&A. My question is far more straight forward and requires a much simpler answer. –  Damien Jul 29 '09 at 5:51

Your Answer


