Alex Rivera | Logout

Null safe way to get values from an IDataReader

Asked 2010-04-09T18:26:41.813
12
(LocalVariable)ABC.string(Name) = (IDataReader)dataReader.GetString(0);

This name value is coming from database.

What happening here is if this name is null while reading it's throwing an exception?

I am manually doing some if condition here. I don't want to write a manual condition to check all my variables.

I am doing something like this now..

String abc = dataReader.GetValue(0);
if (abc == null)
   //assigning null
else
   //assigning abc value

Is there something like can we write extension method for this?

Edit
Report

2 Answers

2

My solution is that:

private static T GetValue<T>(object o) {
    if (typeof(DBNull) != o.GetType()) {
        return (T) o;
    }
    return default(T);
}

When, Status = GetValue<string>(currentDataRow["status"])

answered 2011-04-01T23:18:50.240
0

I'd use something like this:

string abc = (IDataReader)datareader.GetValue(0) ?? "Default";
answered 2010-04-09T18:31:10.877

Your Answer