Simpler pattern for SqlConnection
Posted by Michael Bray on August 8, 2008
In our May Contest, there was a post about SqlConnection pattern:
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
//add commands and execution here
}
catch(Exception ex)
{
string error = ex.Message; //do something with the error
}
finally
{
if(conn.State == ConnectionState.Open) conn.Close();
}
}
With the try/catch there to make sure the connection gets closed. Well it turns out that the try/catch in this statement is unnecessary, since the Dispose(…) on SqlConnection performs a Close() on the connection anyway… here’s the disassembled code from Dispose(…):
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
So the original code can simplify down into:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
…
}