You only need to dispose object of the types implementing
System.IDisposable
. Please see:
http://msdn.microsoft.com/en-us/library/system.idisposable.aspx[
^].
If you work with temporary object, the best way of doing it is using the
using
statement, which helps to dispose the object you create even if an exception is thrown. Actually, it works exactly like with try-finally block:
http://msdn.microsoft.com/en-us/library/htd05whh.aspx[
^].
If you use your objects beyond the scope of a single method, you need to use the chain strategy: dispose everything in the parent's dispose method. …OK, it looks like I'm going to far from the original topic… :-)
[EDIT]
You should not mix up disposal with managed memory allocation. You never need to do anything to release it, the
garbage collector does it:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[
^].
Actually, this is why .NET (CLR) code is called "managed".
The interface
System.IDisposable
can be used for any purposes which do not have to be related to release of something. Rather, it is used as a mechanism to guarantee that some "closing" action is always performed. One of the most typical application of this mechanism is the release of unmanaged resources, as in the case of GDI object. This is an interesting example of using disposing not related to releasing of anything:
Hourglass Mouse Cursor Always Changes Back to its Original Image. How?[
^] (please also see the alternative solution, which is more generalized).
—SA