Justin
Justin

Reputation: 1310

If SqlDataReader is going to be disposed, do I need to call close()?

If I instantiate a SqlDataReader inside a using block, do I need to call close() on the reader?

Simple example of looking up a user shown below.

  using (var connection = new SqlConnection(Settings.GetValue("SqlConnection")))
  {
    SqlCommand command = new SqlCommand("select * from Users where Id = @Id", connection);        
    command.Parameters.Add("@Id", SqlDbType.UniqueIdentifier);
    command.Parameters["@Id"].Value = id;

    using (SqlDataReader reader = command.ExecuteReaderWithRetry())
    {
      reader.Read();

      if (reader.HasRows)
      {
        //Do work
      }

      //Is this neccesary?
      reader.Close();
    }
  }

Upvotes: 3

Views: 1061

Answers (1)

mike
mike

Reputation: 329

If it's in a using block, then it is automatically closed. You do not need to explicitly close it.

BTW the SqlCommand in your example is disposable. You should create it in a using block too, otherwise any resources it controls won't be let go until the garbage collector collects.

Your undisposed SqlCommand is actually a good example of why C#'s emulation of RAII is not "real" RAII. You must take an explicit action (making blocks) for the RAII to kick in which is equivalent to an explicit close albeit with different syntax.

Upvotes: 12

Related Questions