Water said:
I heard from someone that we must not implement IDisposable for all
classes. Can someone please tell me:
1. the reason why we must not implement IDisposable for all the classes
we write.
It's the same reason you don't implement IEnumerator, IAsyncResult,
etc. If it's not needed don't bother. Here are few general guidelines
that may help determine if it's needed.
* DO implement IDisposable if your class directly uses unmanaged
resources. For example, a handle obtained from the Win32 API, etc.
* DO implement IDisposable if your class indirectly uses unmanaged
resources. For example, if your class has a reference to another
object that implements IDisposable.
* DO override the Finalize method if your class directly uses unmanaged
resources.
* DON'T override the Finalize method if your class does not directly
use managed resource. In other words, don't override Finalize just
because your class has a reference to another class that implements
IDisposable.
* DON'T override the Finalize method in a class who's base class
already overrides Finalize. In other words, if the base class provides
the protected Dispose(disposing as Boolean) method then you don't need
to override Finalize.
* DON'T implement IDisposable if your class does not hold unmanaged
resources either directly or indirectly. For clarity, I don't consider
objects whose scope is limited to methods as being held by the class
itself. If a method in your class uses an IDisposable object locally
then just make sure it's Dispose method is called before the method
ends.
2. what is the correct way of implementing IDisposable.Dispose?
See the MSDN documentation.
http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx
Also, consider using the SafeHandle class.
3. what is the preferred way, if there is one over the other, of
calling the Dispose method on an object that implements IDisposable. Is
it the way that uses the "using(object){}" construct or the way that
emphasises on explicitly calling the Dispose method on the object?
Well, I can tell you that I prefer to use the 'using' keyword, but
sometimes it just makes more sense to call Dispose explicitly.