SqlCommand with using statement

Total Post:108

Points:756
C# 
C#
 1070  View(s)
Ratings:
Rate this:

I saw that in most samples SqlCommand was used like this

using (SqlConnection con = new SqlConnection(CNN_STRING))
{
    using (SqlCommand cmd = new SqlCommand("Select ID,Name From Person", con))
    {
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds =new DataSet();
        da.Fill(ds);          
        return ds;
    }
}

I know why we are using "using" statement. But SqlCommand doesn't inlcude Close() method, so should we really use it within using statement

  1. Post:412

    Points:2888
    Re: SqlCommand with using statement

    SqlCommand does implement IDisposable which a using statement will call .Dispose() on before the using block is finished. it's a good idea to call .Dispose() on an instance you are finished with i.e. it will clear up a database connection perhaps.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!