Using the SqlDataReader
class, what, if any, are the functional differences between:
(string) dataReader["MyFieldName"];
and
dataReader.GetString(dataReader.GetOrdinal("MyFieldName"));
Casting issues aside, for the singular call, there are none. The indexer will make a call to DbDataReader.GetOrdinal
and then call the appropriate Get
method to get the value (note that it's faster to call the Get
methods using an ordinal than it is to use the indexer with the field name).
However, this will incur a lookup of the ordinal every time. If you are iterating through a number of records in a forward-only, read-only way (which is exactly what DbDataReader
instances are meant to do), then you can reduce the overhead of this lookup by doing it just once.
You could do so like this:
// Move to the first record. If no records, get out.
if (!dataReader.Read()) return;
// Before the loop. Can do this for any other fields being
// accessed in the loop as well.
int myFieldNameOrdinal = dataReader.GetOrdinal("MyFieldName");
// Process the records. Remember, already on the first record, so
// use do/while here.
do
{
// Do something with your field.
Console.WriteLine(dataReader.GetString(myFieldNameOrdinal));
} while (dataReader.Read());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With