Why use the GetOrdinal() Method of the SqlDataReader

Tesseract picture Tesseract · Jul 3, 2009 · Viewed 25k times · Source

What's the difference between reading a value from an SqlDataReader using this syntax:

Dim reader As SqlClient.SqlDataReader
reader("value").ToString()

OR

Dim reader As SqlClient.SqlDataReader
reader.GetString(reader.GetOrdinal("value"))

Answer

Alex Black picture Alex Black · Jul 3, 2009

I think that the reason to use GetOrdinal() is so that you can cache the result and re-use it multiple times for performance.

E.g.

Dim reader As SqlClient.SqlDataReader
int valueOrdinal = reader.GetOrdinal("value");
while ( ... )
{
    var value = reader.GetString(valueOrdinal);
}