Posts Tagged 'generics'

Dealing with DBNull in DataReaders

When dealing with IDataReaders in .NET, one faces the problem of catching DBNull values and properly converting them to ‘native null’:

int? myNullableField = (int?) reader["myField"]; // will FAIL if DBNull is being returned..

This extension method eases this pain and allows to retrieve the values in a null-safe way:

    public static class IDataReaderExtensions
    {
        public static Nullable<T> GetNullableValue<T> (this IDataReader reader, string fieldName) where T : struct
        {
            object value = reader[fieldName];
            if (value == DBNull.Value)
                return null;

            return (T) value;
        }
    }

Using the above extension, you can now simply use the reader this way:

int? myNullableField = reader.GetNullableValue<int>("myField");

The Nullable generic type does not work with certain types such as string, therefore the constraint T : struct is really essential to get it working. I borrowed this constraint trick from stackoverflow.com

Happy coding..