If .NET has garbage collection then why do you have to explicitly call IDisposable
?
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.