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.


VulpesRank #55 · 29.2K reputationPosted Jul 12, 2014, 4:47 AM EDT
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.
Guest UserRank #259 · 9.8K reputationPosted Jul 12, 2014, 4:48 AM EDT
And, It is highly recommended to Dispose IDisposable objects manually.
twitter @sumitjolly
Ken HRank #2,315 · 610 reputationPosted Jul 12, 2014, 6:29 AM EDT
Thanks.
VulpesRank #55 · 29.2K reputationPosted Jul 12, 2014, 6:33 AM EDT
Mahesh ChandRank #1 · 393.3K reputationPosted Jul 13, 2014, 6:44 AM EDT