Random Noise

cat /dev/random >> /dev/dsp

Archive for July 2009

IDataReader GetValue Extension method

with 2 comments

It is offten desired to get a value from DataReader using column name with known Type. For example you want to get a string value of column ‘first_name’ and int value of column ‘account_number’. The following extension method makes it easy to fetch values from a DataReader using Type and column name:

public static class ReaderHelper
    public static bool IsNullableType(Type valueType)
        return (valueType.IsGenericType &&

    public static T GetValue<T>(this IDataReader reader, string columnName)
        object value = reader[columnName];
        Type valueType = typeof(T);
        if (value != DBNull.Value)
            if (!IsNullableType(valueType))
                return (T)Convert.ChangeType(value, valueType);
                NullableConverter nc = new NullableConverter(valueType);
                return (T)Convert.ChangeType(value, nc.UnderlyingType);
        return default(T);

It can be used as:

User GetUser(IDataReader reader)
    User user = new User();
    user.FirstName = reader.GetValue<string>("first_name");
    user.LastName = reader.GetValue<string>("last_name");
    user.Email = reader.GetValue<string>("email");
    user.AccountNumber = reader.GetValue<int>("account_number");
    user.NumberOfVehiclesOwned = reader.GetValue<int?>("vehicle_count"); // nullable data field
    return user;

Written by Vivek Unune

July 15, 2009 at 9:27 pm

Posted in .NET

Tagged with ,