DataReader GetInt32

  • Thread starter Thread starter mike parr
  • Start date Start date
M

mike parr

When reading from a data reader I have been using code like this :

if (objDataReader.Read() == true)
{
intNewStatus =
Convert.ToInt32(objDataReader["STATUS"]);
}

But I've seen some code examples using GetInt32 (or GetString etc). Is
there any difference between using these 2 methods, and which one is
recommended?



Thanks,

Mike
 
mike parr said:
When reading from a data reader I have been using code like this :

if (objDataReader.Read() == true)
{
intNewStatus =
Convert.ToInt32(objDataReader["STATUS"]);
}

But I've seen some code examples using GetInt32 (or GetString etc). Is
there any difference between using these 2 methods, and which one is
recommended?

Personally I'd use GetInt32() etc - it makes your code clearer, IMO.
 
It's probably obvious to everyone, but one subtle difference in actual
functionality is that the GetInt32() demands that the native type is already
an integer, while the other will be happy to convert from a double, for
example. One might argue that using the more strict option would be a way
to ensure a higher degree of integrity (the database type is still what you
expected).

Jon Skeet said:
mike parr said:
When reading from a data reader I have been using code like this :

if (objDataReader.Read() == true)
{
intNewStatus =
Convert.ToInt32(objDataReader["STATUS"]);
}

But I've seen some code examples using GetInt32 (or GetString etc). Is
there any difference between using these 2 methods, and which one is
recommended?

Personally I'd use GetInt32() etc - it makes your code clearer, IMO.
 
Mike, as an aside, using the nominal reference "STATUS" as opposed the an
index (if status was the first field in your query, using [0] instead) can
have some performance implications. If you are doing it for one field, it
will probably be trivial, but it's still wasteful in the the Named column's
index needs resolved at every pass even though it only takes one time to
figure it out.

there are two cool ways (other than just coding the indexes which hampers
readability quite a bit unless you really comment it well).

You can delcare an intere and use the dataReader's .GetOrdinal Method. So
the int variables has a clear name (like the actual column name) and now you
can use Status instead of "Status" is you delcared an int Status and used
the GetOrdingal mehtod. Just do this outside of the read loop.

You can also create an Enum (Bill Vaughn's idea) which circumvents the need
to even use GetOrdinal while getting you to the same end result.

HTH,

Bill
 
Back
Top