5
Answers

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

Ken H

Ken H

10y
929
1
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)