When should I use the using Statement? [duplicate]

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();
}

Leave a Comment