i took this code from msdn
string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
}
}
as you can see there is no using for the SqlCommand here, so, does it needs to be ?
You need a
usingfor every object you create that implementsIDisposable. That includes theSqlCommandand theSqlConnection.There are very few exceptions to this rule. The main exception is WCF client proxies. Due to a design flaw, their
Disposemethod can sometimes throw an exception. If you used the proxy in ausingstatement, this second exception would cause you to lose the original exception.