I have a class:
public abstract class BaseComponent { ... }
Within the constructor of that class we subscribe to an event handler e.g.
protected ObjectWithEventHandler eventObject { get; private set; }
public BaseComponent (ObjectWithEventHandler obj)
{
eventObject = obj;
eventObject.ChangedEvent += new EventHandler(eventObject_OnChangedEvent );
}
protected void eventObject_OnChangedEvent (object sender, EventArgs e) { ... }
Are there any hard and fast rules when it comes to EventHandler subscription & unsubscription?
Is it considered good practice to provide some clean-up code that unsubscribes the function from the EventHandler? I.e. implement IDisposable and unsubscribe from the EventHandler then?
Or am I worrying unduly?
If you have full control of the usage of BaseComponent and you know that EventObject’s lifecycle is shorter or equal* with regard to BaseComponent’s lifecycle, you can skip unsubscription code.
In all other cases I would include it. In this case implementing IDisposable is good style.
*) effectively, you are coupling eventObject’s lifetime to BaseComponent, so it cannot live shorter, but it could still be equal when the two go out of scope together.