Search code examples
c#usingusing-statement

C# using statement catch error


I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:

 using (SqlCommand cmd = 
     new SqlCommand(reportDataSource, 
         new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString)))
 {
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
     cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
     cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
     cmd.Connection.Open();

     DataSet dset = new DataSet();
     new SqlDataAdapter(cmd).Fill(dset);
     this.gridDataSource.DataSource = dset.Tables[0];
 }

This seems to work but is there any point in this since as far as I can tell I would still need to enclose this in a try catch block to catch unforseen errors e.g. sql server down. Am I missing something?

As far as I can currently see it just stops me closing and disposing of cmd but there will be more lines of code due to the try catch still being needed.


Solution

  • This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection:

    using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
    using (SqlCommand cmd = new SqlCommand(reportDataSource, con))
             {
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
                 cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
                 cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
                 cmd.Connection.Open();
    
                 DataSet dset = new DataSet();
                 new SqlDataAdapter(cmd).Fill(dset);
                 this.gridDataSource.DataSource = dset.Tables[0];
             }
    

    To answer your question, you can do the same in a finally block, but this scopes the code nicely and ensures that you remember to clean up.