Search code examples
c#disposeusingidisposable

C# will Dispose still get called in this situation?


Is the following code the same, eg will dispose still get called?

If I use a using statement, like this, I know Dispose will get called:

using (SqlCommand cmd = new SqlCommand(procedureName, sqlConnection))
{
   cmd.CommandType = CommandType.StoredProcedure;
   if (sqlParams != null)
        cmd.Parameters.AddRange(sqlParams.ToArray());

   SqlDataReader rdr = cmd.ExecuteReader();
   return rdr;
}

My question is, is the effectively the same thing:

SqlCommand cmd = new SqlCommand(procedureName, sqlConnection)
using (cmd)
{
   cmd.CommandType = CommandType.StoredProcedure;
   if (sqlParams != null)
        cmd.Parameters.AddRange(sqlParams.ToArray());

   SqlDataReader rdr = cmd.ExecuteReader();
   return rdr;
}

Solution

  • Yes - anything you can call Dispose() on will be disposed of automatically when the code exits the using() block, including in the example you give above.