Trying to understand when implementation of IDisposable is necessary:
I wrote a little example.
public class FileManager
{
private FileStream fileStream;
public void OpenFile(string path)
{
this.fileStream = File.Open(path, FileMode.Open, FileAccess.Read);
}
public void CloseFile(string path)
{
if ( this.fileStream != null && this.fileStream.CanRead)
{
this.fileStream.Close();
}
this.fileStream.Dispose();
}
}
// client
var manager = new FileManager();
manager.Open("path");
manager.Close("path");
Does this class need to implement IDisposable because it has a managed resource (FileStream) which holds onto an unmanaged resource (a file)? Or do I not have to implement IDisposable because I am cleaning up within the class?
Confused.
For every instance of any type which implements
IDisposableand might do so in a non-trivial fashion, it must at every moment be possible to identify how that instance will beDisposed. In most cases, this means that eachIDisposableinstance will have a well-defined owner, which is responsible for callingDispose. In the case of theFileStreaminstance created by the class, your class is the owner, since nothing else will be able toDisposeit.Classes with fields that references to
IDisposableinstances which they own should almost always implementIDisposable, and use theirDisposemethod toDisposetheIDisposableobjects they own. Your class has such a field; it should thus implementIDisposable.Whenever possible, a class which requires cleanup should be designed so that calling
IDisposable.Disposeon it will suffice to perform any and all such cleanup as may be needed. In some cases, it may be impractical to perform cleanup without using some other method, but those cases are pretty rare. If one can design a class so thatDisposewill take care of all necessary cleanup, one should do so.