Search code examples
c#.netdisposeunmanagedtextreader

What C# class objects acquire unmanaged resources? Is there a list?


I was working on serializing and deserializing a class object using XML when I came across this blog post that shows how to do it on Windows Phone 7 using the isolated storage area. Windows Phone 7 is the platform I am developing for:

In this example, the only object he explicitly calls Dispose() on is the TextReader object. I looked up the TextReader object on MSDN and found that the documentation said this:

Releases the unmanaged resources used by the TextReader and optionally releases the managed resources.

So I assume the reason he does this is to release immediately the unmanaged resources acquired by the TextReader object. It would not have occurred to me to do this if it weren't for his blog post. Obviously I don't want to start calling Dispose() on every object in sight, so what is a good rule of thumb for at least investigating when a particular object should have Dispose() called on it or not? Are there some guidelines for this or a list somewhere, at least of the popular .NET objects that require this special handling?


Solution

  • Obviously I don't want to start calling Dispose() on every object in

    Wrong.

    In general, any object that implements IDisposable should be disposed as soon as you're finished with it, typically using the using statement.

    Most objects that do not have unmanaged resources do not implement IDisposable (and do not have Dispose() methods), so you have nothing to worry about.

    The only exceptions are base classes that implement IDisposable in case some derived implementations have something to dispose (eg, IEnumerator, Component, or TextReader).
    However, it is not always obvious which concrete implementations need to be disposed (and it may change at any time), so you should always dispose them anyway.