CTICoder

A random spillage of programming (and other) thoughts

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: