DataReader in using blocks executes the "Close ()" of the DataReader?

4

I have a little doubt regarding DataReader's within using blocks. If the 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?

Here is a sample DataReader with the using block:

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

Is it right, or do I have to insert a Close ()?

using(var dr = myCommand.ExecuteReader())
{
    //...Código
    dr.Close()
}
    
asked by anonymous 04.08.2014 / 21:02

1 answer

4
  

I'm assuming you mean DbDataReader "or one of its subclasses (eg SqlDataReader ), but you can adapt the response if I am engaging. >

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

The function of the using command is to ensure that all IDisposable is correctly finalized at the end of the block - usually, or through an exception. This means that the Dispose method will be called, if it is not null of course (i.e. if there is exception during its creation, there is no way to terminate it).

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

It is equivalent to:

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

DbDataReader implements the IDisposable interface, and the documentation for your method Dispose says:

  

Releases resources used by DbDataReader and calls Close .

That is, it is not necessary to call Close manually, using itself will take care of it for you.

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

    
04.08.2014 / 23:41