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

Happy coding..


1 Response to “Dealing with DBNull in DataReaders”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: