When should I use the using Statement?

JonHiggens picture JonHiggens · Apr 7, 2012 · Viewed 22.7k times · Source

Possible Duplicate:
What is the C# Using block and why should I use it?

I'm converting an old site to C# and I'm not sure when I should be using 'using'. Are there any general guidelines? I know of the benefits, but I'm not 100% sure how to use it. Is it every time I 'new' a method/property?

SqlConnection awesomeConn = new SqlConnection(connection);

Answer

Jackson Pope picture Jackson Pope · Apr 7, 2012

If a class implements IDisposable then it will create some unmanaged resources which need to be 'disposed' of when you are finished using them. So you would do something like:

SqlConnection awesomeConn = new SqlConnection(connection);

// Do some stuff

awesomeConn.Dispose();

To avoid forgetting to dispose of the resourses (in this case close the database connection), especially when an exception is thrown, you can use the using syntax to automatically call dispose when you go out of the using statement's scope:

using (SqlConnection awesomeConn = new SqlConnection(connection))
{
     // Do some stuff
} // automatically does the .Dispose call as if it was in a finally block

In fact, the using block is equivalent to:

try
{
    SqlConnection awesomeConn = new SqlConnection(connection);

    // do some stuff
}
finally 
{
    awesomeConn.Dispose();
}