DataReader best-practices

AJ. picture AJ. · Dec 6, 2009 · Viewed 13.2k times · Source

Similar to this question, but the answers never really got around to what I want to know. Is there any standards around getting values from a DataReader? I.e., is this

dataReader.GetString(dataReader.GetOrdinal("ColumnName"));

considered better/worse/the same as this?

(string) dataReader["ColumnName"];

Answer

Andrew Hare picture Andrew Hare · Dec 6, 2009

Here is the way that I do it:

Int32 ordinal = dataReader.GetOrdinal("ColumnName");

if (!dataReader.IsDBNull(ordinal))
    yourString = dataReader.GetString(ordinal);

It is important to check for DBNull like I have shown above because if the field is null in the DataReader it will throw an exception when you try to retrieve it.