User
User

Reputation: 3274

Is the following pattern acceptable?

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

Answers (4)

DoctorMick
DoctorMick

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

Daniel Hilgarth
Daniel Hilgarth

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

Ankur
Ankur

Reputation: 33657

I would prefer using the "using" block as:

using(<your reader object>)
{
   //read data from reader
}

Upvotes: 3

leppie
leppie

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

Related Questions