DataReader NULL values

One way to deal with possibly-NULL string values from a datareader is to check for NULL first, e.g.


string myvalue;
if (myDataReader["MyField"] != System.DBNull.Value)
myvalue = myDataReader.GetString(myDataReader.GetOrdinal("MyField"));
else
myvalue = "";

But a less-code way is to just let the Convert object handle them for you:

string myvalue = Convert.ToString(myDataReader["MyField"]);

It may not perform quite as well as explicit checking, though, so don’t use it in a tight loop if you’re concerned about performance.

0