Ken H

Ken H

  • NA
  • 646
  • 361.7k

How to correctly use the 'using' statement frees resources?

Jul 12 2014 6:55 AM
Hi all,
    
 Which of the following is correct?  Is there a better way to make it more to save resources?
 
The first version:
 
public static DataTable ExecuteGetTable(string connstring) {
DataSet ds;
using (SqlConnection connection=new SqlConnection(connstring))
{
SqlCommand command = new SqlCommand(connstring);
SqlDataAdapter adapter = new SqlDataAdapter();
connection.Open();
adapter.SelectCommand = command;
ds = new DataSet();
adapter.Fill(ds);
}
return ds.Tables[0];
}
 
The second version:
 
public static DataTable ExecuteGetTable(string connstring) {
DataSet ds;
using (SqlConnection connection=new SqlConnection(connstring))
{
using (SqlCommand command = new SqlCommand(connstring))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
connection.Open();
adapter.SelectCommand = command;
ds = new DataSet();
adapter.Fill(ds);
}
}
}
     return ds.Tables[0];
}
 
Thanks. 

Answers (5)