Possible Duplicate:
Trying to understand the ‘using’ statement better
I've really read all other posts, but no one really answers my question.
This is my function that returns a table
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(mainConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
return dt;
}
what's the advantage of the previous against the following (the one that I always used prior to discover 'using'):
public DataTable ReturnTable()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(mainConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
SQL = " SELECT * from table";
cmd.CommandText = SQL;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
With the second, aren't con, cmd and da properly disposed? Is there anything wrong with the second?
Thanks!