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
}
精彩评论