To clear up your general question of when to do Dispose and Finalize:
If you have a field in your class that is a IntPtr
(or some other kind of unmanaged resource, but a IntPtr
is the most common) and it is your classes responsibility to clean up that resource then you need to implement a finalizer. In that finalizer you should deallocate whatever resource the IntPtr
points too. If you don't have a IntPtr then the class you are holding on to should be handling its own finalization and would implement IDisposeable
(see the next part)
If you have a field in your class that implements IDisposable
and your class is responsible for cleaning up after that object your class should also implement IDisposable
and in that dispose method you should call Dispose()
on the object.
For event handlers, it is a matter of personal preference. You can, but it only matters if you do or not if the person who subscribed to the event messed up their code.
Unless you expect the publisher of the event to outlive the
subscriber, there's no reason to remove the event handler...
I personally do not, but I do know some people who do. If you wanted to do it, the process is simply setting the event handler to null
in your dispose method.
public sealed class Example : IDisposable
{
public EventHandler MyEvent;
public void Dispose()
{
MyEvent = null;
}
}
EDIT: And a good point that Hans Passant brought up in the comments: You never need a finalizer, if you have a unmanaged resource that would need a finalizer it should get wrapped up in a SafeHandle
wrapper to handle the finalization for you. Once you do that the object just becomes another normal IDisposable
you need to take care of in your .Dispose()
method.