Proper use of the IDisposable interface

Posted by cwick on Stack Overflow See other posts from Stack Overflow or by cwick
Published on 2009-02-11T18:12:41Z Indexed on 2010/04/01 21:13 UTC
Read the original article Hit count: 368

Filed under:
|

I know from reading the MSDN documentation that the "primary" use of the IDisposable interface is to clean up unmanaged resources http://msdn.microsoft.com/en-us/library/system.idisposable.aspx.

To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the Dispose method is implemented to free managed resources, which seems redundant to me, since the garbage collector should take care of that for you.

For example:

public class MyCollection : IDisposable
{
    private List<String> _theList = new List<String>();
    private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();

    // Die, you gravy sucking pig dog!
    public void Dispose()
    {
        _theList.clear();
        _theDict.clear();
        _theList = null;
        _theDict = null;
    }

My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would?

edit: So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that _theList in the above code contained a million strings, and you wanted to free that memory now, rather than waiting for the garbage collector. Would the above code accomplish that?

© Stack Overflow or respective owner

Related posts about c#

Related posts about garbage-collection