Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET SqlDataReader Item[] vs. GetString(GetOrdinal())?

Tags:

.net

Using the SqlDataReader class, what, if any, are the functional differences between:

(string) dataReader["MyFieldName"];

and

dataReader.GetString(dataReader.GetOrdinal("MyFieldName"));
like image 523
Sako73 Avatar asked May 16 '11 16:05

Sako73


1 Answers

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());
like image 95
casperOne Avatar answered Nov 05 '22 02:11

casperOne