tags:

views:

472

answers:

4

What's the purpose of implementing the IDisposable interface? I've seen some classes implementing it and I don't understand why.

+8  A: 

If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.

Ed Swangren
+5  A: 

When your classes makes use of some system resource, it's the class' responsibility to make sure the resource is freed too. By .Net design you're supposed to do that in the Dispose method of the class. The IDisposable interface marks that your class needs to free resource when it's no longer in use, and the Dispose method is made available so that users of your class can call it to free the consumed resources.

The IDisposable method is also essential if you want auto clean-up to work properly and want to use the using() statement.

Cyril Gupta
+2  A: 

It all has to do with the garbage collection mechanism. Chris Sells describes garbage collection, finalizers, and the reason for the Dispose pattern (and the IDisposable interface) episode 10 of .NET Rocks! (starting about 34 minutes in).

Rob Windsor
+3  A: 

As well as freeing unmanaged resources, objects can usefully perform some operation the moment they go out of scope. A useful example might be an timer object: such objects could print out the time elapsed since their construction in the Dispose() method. These objects could then be used to log the approximate time taken for some set of operations:

using(Timer tmr=new Timer("blah"))
{
    // do whatever
}

This can be done manually, of course, but my feeling is that one should take advantage wherever possible of the compiler's ability to generate the right code automatically.

brone