tags:

views:

35

answers:

2

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 ?

+7  A: 

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.

John Saunders
+1, but to be perfectly clear on the WCF issue: it doesn't mean that you should just ignore that the client is disposable. Rather, it means that you should wrap the call in a try/finally block and wrap the Close/Dispose operation inside the finally block in a try/catch block. Very ugly, though...
Mark Seemann
+1  A: 

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.

David Stratton
`IDisposable` isn't about memory usage. It's about _resource_ usage.
John Saunders
I thought that since the connection was used to create the command, than when you dispose it the command will also get disposed
Omu
but presumably the SqlCommand isn't holding any resources open, since the Connection that created the SqlCommand has been closed...
rohancragg
@Omu: No, not documented as such, so assume it's not true.
John Saunders
@rohancragg: I wouldn't make assumptions about something like that. Even if it were true in the current release, it may not be true in some future release.
John Saunders
fair enough, I agree anyway, I'd personally put the using in wherever possible
rohancragg