My project has many reader and writer classes. I started implementing IDisposable, but I believe that it adds many boilerplate code to my classes. For each of the classes, I need to implement:
- A destructor.
- A Dispose() method.
- A Dispose(bool disposing) method.
- A "bool disposed" field.
- A check to see if the object is already disposed on every single public method.
- Documentation (since I have the documentation flag enabled and the compiler warns otherwise).
My questions:
Is it worth to implement IDisposable? Previously, I used my classes like:
using (Stream s = File.OpenRead("myfile.bin"))
x = new SomethingReader(s).ReadSomething();
With IDisposable, it doesn't improve much:
using (SomethingReader r = new SomethingReader(File.OpenRead("myfile.bin")))
x = r.ReadSomething();
Can I ONLY implement the Dispose() method?
My class doesn't use unmanaged resources, so Dispose(false) does nothing. Since what I'm cleaning is IDisposable too, suposedly calling my methods after the object has been disposed should throw a ObjectDisposedException since I'm using an already disposed object.
If you recommend implementing the full IDisposable pattern, is there any way to reduce the boilerplate code?
EDIT: Since some answers recommend sealing the class, I can confirm that, in fact, there isn't any problem by sealing the class.