Extending IDataReader

I like to access my DataReader objects via column name. Unfortunately, IDataReader supports getting items via integer indexer.

To overcome this *obstacle*, I’ve written an extension method I’d like to share. It checks to see whether a column exists and has a value associated with it.

 public static class IDataReaderExtension
  {
      /// <summary>
      /// Adds the HasValue property to an IDataReader, which checks based on Column name
      /// </summary>
      /// <param name="reader">An IDataReader object</param>
      /// <param name="column">The string column name</param>
      /// <returns>boolean</returns>
      public static bool HasValue(this IDataReader reader, string column)
       {
           if (reader.GetSchemaTable().Columns.Contains(column))
               return reader[column] != null || reader[column] != DBNull.Value;
           else
               return false;
       }
   }
 

In order to use this method, you can now check:

if(reader.HasValue("MY_COLUMN"))
{
    myObject.ColumnInfo = Convert.ToString(reader["MY_COLUMN"]);
}