What is IDisposable for?

FendFend picture FendFend · Mar 5, 2009 · Viewed 8.7k times · Source

If .NET has garbage collection then why do you have to explicitly call IDisposable?

Answer

Jon Skeet picture Jon Skeet · Mar 5, 2009

Garbage collection is for memory. You need to dispose of non-memory resources - file handles, sockets, GDI+ handles, database connections etc. That's typically what underlies an IDisposable type, although the actual handle can be quite a long way down a chain of references. For example, you might Dispose an XmlWriter which disposes a StreamWriter it has a reference to, which disposes the FileStream it has a reference to, which releases the file handle itself.