Friday, February 12, 2010

Best practices using IDisposable

Recently I had some mess with resources leak in some .Net system that was caused by miss use of IDisposable objects.

In this post you can find brief summary of disposable objects use cases. Hope it will help to write better code.

Disposable as parameter

public void ReadYourPart(Stream data)
 // Read from stream   
 // And leave it opened, do not dispose it

In this case I would like to consider function that receives some disposable resource as parameter, stream in example above. Since it is impossible to know the scope where this resource must be available you don’t want to dispose it. Just live it alone when you finished.

Disposable as class member

If you have to write class with disposable member you must add implementation of IDisposable interface to your class.

public class MyClass : IDisposable
  private IDisposable resource;
  public MyClass(IDisposable resource)
    this.resource = resourse;



Here responsibility to dispose the resource is delegated to the user of MyClass via it dispose method.


And finally if you instantiating IDisposable so you are responsible to dispose it. And of course the best way to use using clause.

using (Stream data = new FileStream("data.dat", FileMode.Open))
   // dara usage comes here

I would also call dispose for resource returned by some function like in example below:

using (IDisposable someResource = factory.OpenResource())
   // resource usage comes here

Happy coding!