C# using Statement

Memory management is often a major consideration in software development. Memory leaks wreak havoc on systems and are depressingly common mistakes. One tool you can use to help avoid memory leaks in C# applications is the “using” statement.

Using statements provide ad hoc scope/encapsulation for an object that implements the IDisposable interface (Streams, Database Commands, etc.). If you know you’re only going to use a Stream locally and within a single function, you can throw it in a using statement and the memory allocated for it will be automatically released when the program leaves the code block.

Having used using statements for a while now, I was curious as to what exactly the syntax was compiling into functionally (in the specific case, determining whether or not I needed to verify that my variable wasn’t null). This article on Code Project explained it for me:

Syntax for a using statement (with a FileStream)

[sourcecode light=”true” language=”csharp”]
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
//file stream codes here
fs.Close();
}
[/sourcecode]

What the execution essentially does

[sourcecode light=”true” language=”csharp”]
FileStream fs = new FileStream(filename, FileMode.Create);
try
{
//file stream codes here
fs.Close();
}
finally
{
// Check for a null resource.
if (fs != null)
// Call the object’s Dispose method.
((IDisposable)fs).Dispose();
}
[/sourcecode]

Tagged with: ,
Posted in Blurbs