.NET Framework Unmanaged Resources


Example

When we talk about the GC and the "heap", we're really talking about what's called the managed heap. Objects on the managed heap can access resources not on the managed heap, for example, when writing to or reading from a file. Unexpected behavior can occur when, a file is opened for reading and then an exception occurs, preventing the file handle from closing as it normally would. For this reason, .NET requires that unmanaged resources implement the IDisposable interface. This interface has a single method called Dispose with no parameters:

public interface IDisposable
{
    Dispose();
} 

When handling unmanaged resources, you should make sure that they are properly disposed. You can do this by explicitly calling Dispose() in a finally block, or with a using statement.

StreamReader sr; 
string textFromFile;
string filename = "SomeFile.txt";
try 
{
    sr = new StreamReader(filename);
    textFromFile = sr.ReadToEnd();
}
finally
{
    if (sr != null) sr.Dispose();
}

or

string textFromFile;
string filename = "SomeFile.txt";

using (StreamReader sr = new Streamreader(filename))
{
    textFromFile = sr.ReadToEnd();
}

The latter is the preferred method, and is automatically expanded to the former during compilation.