Reputation: 3274
I am trying to come up myself with an acceptable pattern for data reading from DB using Enterprise Library. How do you consider the following pattern (I mean, the null-check in the finally
block)?
IDataReader NewReader = null;
try
{
NewReader = (SqlDataReader)(SqlDatabase.ExecuteReader(SqlCommand));
/* Do some work with NewReader. */
NewReader.Close();
}
catch /* As much 'catch' blocks as necessary */
{
/* Handle exceptions */
}
finally
{
if (!ReferenceEquals(NewReader, null))
{
NewReader.Dispose();
}
}
Is this null-check acceptable, or is there a more elegant way of solving this problem?
Upvotes: 0
Views: 89
Reputation: 6793
Just to add a bit of detail to what people have said above...
Use a using block as, regardless of whether an exception occurs or not, the Dispose method will automatically be called due to implementations of IDataReader having to also implementing IDisposable.
Upvotes: 0
Reputation: 174457
I would use if(NewReader == null)
. It's the default way of checking for null
. Your way of doing it is the same, but it looks strange and thus might confuse people.
Besides: Why don't you use using
? Makes your code a lot cleaner:
try
{
using(IDataReader NewReader = (SqlDataReader)(SqlDatabase.ExecuteReader(SqlCommand)))
{
/* Do some work with NewReader. */
}
}
catch /* As much 'catch' blocks as necessary */
{
/* Handle exceptions */
}
Upvotes: 5
Reputation: 33657
I would prefer using the "using" block as:
using(<your reader object>)
{
//read data from reader
}
Upvotes: 3
Reputation: 117330
It is the same as:
if (NewReader != null) ...
which I would prefer from a styling point of view.
Update:
As NewReader
seemingly implements IDisposable
, just wrap it in a using
construct.
Example:
using (var r = new ReaderSomething())
{
try
{
}
catch {}
}
Upvotes: 4