开发者

which is better, closing a datareader or setting it to null?

开发者 https://www.devze.com 2023-03-12 22:42 出处:网络
I would like to know the advantage and disadvantage of the following operation shall i bet开发者_JAVA百科ter set the datareader to null than calling the close method. If this is good what are the adv

I would like to know the advantage and disadvantage of the following operation

shall i bet开发者_JAVA百科ter set the datareader to null than calling the close method. If this is good what are the advantages, else what is the problem in using so?.


You should use the using statement instead:

using (var reader = sqlCommand.ExecuteReader())
{
  // do stuff
}

That way, you are sure that the reader is closed (disposed), even if an exception was raised in the "do stuff" block.

For a complete example, see this MSDN page.


Update (regarding your comment):

The using statement is in fact nothing else than a try-finally block to ensure that the reader is disposed (closed) in every case. E.g. the above code is equivalent to this:

SqlDataReader reader = null;
try
{
  reader = sqlCommand.ExecuteReader();
}
finally
{
  reader.Dispose(); // closes the reader
}
0

精彩评论

暂无评论...
验证码 换一张
取 消