Question about Event handlers and GC

  • Thread starter Thread starter Aamir Mahmood
  • Start date Start date
A

Aamir Mahmood

Hi all,
Consider the following code as just an example to understand what I want to
say.

My question is if a class instance subscribes one or more events of another
class. If that instance which implements the event handler goes out of
scope, what will happen to the instance? Will it be eventually freed by the
GC? Or will it never be freed because its reference is added in the list of
event handlers by other class.


public class EventRaisingClass {
public delegate void SomeEventDelegate(object sender);
public event SomeEventDelegate OnSomeEvent;


public void UserMethod() {
EventHandlerClass ehc = new EventHandlerClass();
this.OnSomeEvent += new SomeEventDelegate(ehc.SomeEventHandler);
}
}

public class EventHandlerClass {
public void SomeEventHandler(object sender) {
// do something
}
}
 
Hi Aamir.

This is a non-problem and you almost answered your own question.
As the delegate holds a reference to the implementing instance, that
instance cannot go out of scope.

Regards
- Michael S
 
Back
Top