Does Holding A Delegate Reference Keep The Owning Object Alive?

0 comments suggest edit

I have a big question that can probably be best elucidated via some code:

public class SomeClass
{
    // This guy will raise an important event.
    private EventSource _source = new EventSource();

    public void AttachEventHandler()
    {
        // This guy will handle an important event...
    BigEventListener listener = new BigEventListener();
    _source.BigEvent += new EventHandler(listener.OnBigEvent);

    //What happens to listener instance here?
    //Will it be garbage collected?

    }
}

So what happens after the method AttachEventHandler() is called? I am assuming that the EventHandler delegate’s reference to the OnBigEvent method of the listener instance is a hard reference. In other words,even though listener is a local instance and would normally go out of scope when AttachEventHandler ends, that the listener instance is not collected because of the delegate reference. Is this correct?

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

3 responses

  1. Avatar for Omer van Kloeten
    Omer van Kloeten July 6th, 2004
  2. Avatar for nospamplease75@yahoo.com (Haac
    nospamplease75@yahoo.com (Haac July 6th, 2004

    Thanks Omar. So from these links, I can infer that my object will stay around (which in this case is my intended behavior).

  3. Avatar for Brad Wilson
    Brad Wilson July 6th, 2004

    Yes, delegates are a hard reference. Yes, your object will stay alive. In fact, this can cause of some circular reference memory leaks.