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.

VulpesPosted Jul 12, 2014, 8:47 AM
So the second version is better practice than the first.
Having said this, whilst it's very important to call Dispose() on some objects such as connection or data reader objects, it's less important to call it on others such as command and data-adapter objects. Consequently many programmers (and even some MSDN examples) don't bother with the latter if the object will soon go out of scope as they know that when the destructor runs, just prior to garbage collection, it will clean up the unmanaged resources anyway.
Incidentally, even in these latter cases, calling Dispose() may improve performance because it may suppress finalization which means that the destructor won't be called at all.
Mahesh ChandPosted Jul 13, 2014, 10:44 AM
VulpesPosted Jul 12, 2014, 10:33 AM
Ken HPosted Jul 12, 2014, 10:29 AM
Thanks.
Guest UserPosted Jul 12, 2014, 8:48 AM
And, It is highly recommended to Dispose IDisposable objects manually.
twitter @sumitjolly