开发者

do we need using for the SqlCommand or is it enough just for the SqlConnection and SqlDataReader

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";

      co开发者_运维技巧nn.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 using for every object you create that implements IDisposable. That includes the SqlCommand and the SqlConnection.


There are very few exceptions to this rule. The main exception is WCF client proxies. Due to a design flaw, their Dispose method can sometimes throw an exception. If you used the proxy in a using statement, this second exception would cause you to lose the original exception.


You don't NEED to use a using statement, but it is good practice and you SHOULD use it. It allows objects using IDisposable to be disposed of automatically.

http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx

Edited to add link and remove inaccurate statement because @John Saunders is right.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜