In .Net the Component class exposes a Disposed event. It also provides a protected member OnDispose(bool disposing).

What is the best practice for a custom component that extends Component? Override OnDispose(bool) or attach an event handler to Disposed on construction?

My feeling is that one should override OnDispose(bool) and seal the class.


+1  A: 

I would recommend overriding the behaviour, as an implementer of your component has access to the event handler and as such could deregister your disposer implementation by accident. I believe that you may also need to do this depending on what your custom component is doing, as you may need to run your disposing tasks before calling to the base disposer if you have stateful objects or external interfaces etc.

+2  A: 

Typically events are used by consumers so that they can be notified when events occur. If you're extending the Type and need to clean up resources you should override Dispose(bool disposing)

Spence is partly right about the Event handler, multiple events can be assigned but the issue is that you can't guarantee the order in which the Events are handled.

Sealing the class often depends on what you're designing.

The FxCop rule also has some good info:

+1 for FxCop rule link
Wim Coenen

As I ever heard about this matter it is a .Net standard that inheritors override base class OnXxxxx methods and users handle Xxxxx events.