Unmanaged Resources

suggest change

The garbage collector tracks the managed heap. An object on that heap can also own something the collector does not track, such as a file handle. If an exception is thrown after the file is opened, the handle will not be closed unless something still runs. A type that owns an unmanaged resource should implement IDisposable. That interface has one parameterless method:

public interface IDisposable
{
    void 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 = null; 
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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents