ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetValueOrDefault<T> for DbDataReader

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

Source

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;
}

Author: Fons Sonnemans

Submitted on: 1 feb. 2009

Language: C#

Type: System.Data.Common.DbDataReader

Views: 7956