First, you are not showing the whole implementation of IDisposable. You are missing two important pieces to the puzzle:
1) Object's finalizer method
2) The
using statement[
^]
The full disposable pattern should look like this:
public void Dispose()
{
Disposing(true);
}
private Dispose(bool disposing)
{
if(disposing)
{
GC.SupressFinalize(this);
}
}
private ~MyClass()
{
Dispose(false);
}
Note that the same method is called from both dispose and finalize. Also note you need to implement all this only if you use unmanaged resources. Without them it gets a lot more simple - you can put all your logic directly into Dispose() and forget about the rest.
Why you should use IDisposable? Because you can the use the using statement:
using(var my = new MyClass())
{
}
So why do you need a finalizer you ask? Because as the author of a class you cannot be sure that the programmers using your class will call dispose or use using. There is no way for you to enforce it. So if you use some unmanaged resources you want to make sure they get released properly. So what good is Dispose() if all can be taken care of automatically? Because generally you want to release resources as soon as possible, not wait for GC to kick in.
There are several good articles here on CodeProject about IDisposable pattern. The last one is great but very technical. Nevertheless I recommend it because of the explanation why IDisposable is actually not good.
*
Understanding and Implementing IDisposable Interface - A Beginner's Tutorial[
^]
*
Implementing IDisposable and the Dispose Pattern Properly[
^]
*
IDisposable: What Your Mother Never Told You About Resource Deallocation[
^]