GetValueOrDefault<T> for DbDataReader

public static class DataAccessHelper {

    public static T GetValueOrDefault<T>(this DbDataReader dr, 
                                                      string name) {
        object value = dr[name];
        if (DBNull.Value == value) return default(T);
        return (T)value;
    }

    public static T GetValueOrDefault<T>(this DbDataReader dr, 
                                                        int index) {
        if (dr.IsDBNull(index)) return default(T);
        return (T)dr[index];
    }

    public static bool IsDBNull(this DbDataReader dr, string name) {
        return dr.IsDBNull(dr.GetOrdinal(name));
    }
}
Example:
private List<Book> CreateTitles(SqlDataReader rdr) {
    List<Book> result = new List<Book>();
    while (rdr.Read()) {
        Book b = new Book();
        
        // NOT NULL columns
        b.ID = (string)rdr["title_id"];
        b.Title = (string)rdr["title"];
        
        // NULL column
        b.Price = rdr.GetValueOrDefault<decimal?>("price");
        
        result.Add(b);
    }
    return result;
}

Description

Helper method to retrieve a nullable value of a column from a datareader.

Details

Double click on the code to select all.

 

;