Datareader blocks using Datareader "Close()"?

Asked

Viewed 103 times

4

I have a little doubt regarding Datareader’s inside using blocks. If my Datareader object is inside a using block, will it be closed at the end of that block? Or do I have to insert the Close method()?

Follow Datareader example with the using block:

using(var dr = myCommand.ExecuteReader())
{
    //...Código
}

All right, or I have to insert a Close()?

using(var dr = myCommand.ExecuteReader())
{
    //...Código
    dr.Close()
}

1 answer

4


I’m assuming you’re referring to DbDataReader or one of its subclasses (e.g..: SqlDataReader), but you can adapt the answer if I’m wrong.

Your first example is correct, there is no need to insert a Close().

The function of the control using is to ensure that all IDisposable is correctly finished when finishing the block - normally, or through an exception. This means that the method will be called Dispose of the same, if it is not null of course (i.e. if there is exception during its creation, there is no way to end it).

using(var dr = CriarDisposable()) {
    // código
}

Is equivalent to:

{
  var dr = CriarDisposable();
  try
  {
    // Código
  }
  finally
  {
    if (dr != null)
      ((IDisposable)dr).Dispose();
  }
}

The DbDataReader implements the interface IDisposable, and documentation of its method Dispose says:

Releases the resources used by DbDataReader and flame Close.

That is, there is no need to call Close manually, the very using takes care of it for you.

P.S. If I’m wrong, and you refer to another class called DataReader, take a look at the documentation if it also implements IDisposable, and what the method Dispose ago.

  • That’s right! In my case is the Oracledatareader, but I wanted to be a little generic, because the bank does not influence the question. Thanks @mgibsonbr!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.