I understand the concept of using using
block when making a connection to sql server from your application, as it will close the connection as soon as it goes out of scope and saving us time to write try catch finally
blocks.
But my question is, Is there any benefits of using using
when initialization a SqlCommand
normally I would do something like:
string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "City";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
But what possible benefits I can get by putting SqlCommand initialization in a using block
?
string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
using(SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con))
{
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "City";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}
}
All the material I have searched online talks about the connection being closed as soon as it goes out of scope, Yes I understand that but putting SqlCommand in using block will it make it any more efficient or not?
Any advice or pointers are much appreciated thank you.