"using” statement in C#

I stumbled across something *VERY* interesting tonight that I never knew about.

usually when connecting to a Database, I manually open, close and dispose all the connection which is infact not necessary! Enter the “using” statement for C#.

This is usually how I would write the block of code:

   1:  SqlConnection sqlConn =  null;
   2:  SqlCommand sqlCmd = null;
   3:   
   4:  try
   5:  {
   6:      sqlConn = new SqlConnection(connectionString);
   7:      sqlCmd = new SqlCommand(“Sql command Here”, sqlConn);
   8:      sqlConn.Open();
   9:      sqlCmd.ExecuteNonQuery();
  10:   
  11:      sqlConn.Close();
  12:  }
  13:  catch(Exception ex)
  14:  {
  15:      //handle exception
  16:  }
  17:  finally
  18:  {
  19:      if (sqlCmd != null )
  20:      {
  21:          sqlCmd .Dispose();
  22:      }
  23:      if (null != sqlConn )
  24:      {
  25:          sqlConn .Dispose();
  26:      }
  27:  }

Whereas all that is really needed is:

   1:  using (SqlConnection sqlConn = new SqlConnection(connectionString))
   2:  {
   3:      using (SqlCommand sqlCmd = new SqlCommand(commandString, sqlConn))
   4:      {
   5:          sqlConn.Open();
   6:          sqlCmd.ExecuteNonQuery();
   7:      }
   8:  }

The using statement automatically disposes what is being used once the code block has run. Might be old news to some but awesome news to me. Its the small things that are so cool to discover

Blogged with Flock

Posted under Development by StevenMcD on Tuesday 4 September 2007 at 7:09 pm

1 Comment »

  1. Comment by JBagley — September 25, 2007 @ 7:55 pm

    Awesome! I so did not know that!

RSS feed for comments on this post. TrackBack URI

Leave a comment