.NET Framework Memory management Unmanaged Resources

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any .NET Framework Question?