Monday, May 12, 2008

Extending IDataReader implementations using extension methods

In my post How to extend classes using extension methods, I write about how to extend classes with your own methods. This time we will extend the IDataReader interface with some new methods to save some typing. Since we extend the interface, our methods will be available in all the classes implementing the IDataReader interface, such as the SqlDataReader.

The IDataReader interface provides methods for getting field values for a given type:


string email = reader.GetString(0);

The problem with these methods are that they only accept the index-position and not the field name. Instead, I would prefer to write the code above like this:


string email = reader.GetString("Email");

In order to do this, we need to create a new static class, which defines some new extension methods:


using System;
using System.Data;

/// 
/// Provides extension methods for the IDataReader interface.
/// 
public static class IDataReaderExtension
{
 public static bool GetBoolean(this IDataReader reader, string name)
 {
  return (bool) reader[name];
 }
 public static Guid GetGuid(this IDataReader reader, string name)
 {
  return (Guid) reader[name];
 }
 public static int GetInt(this IDataReader reader, string name)
 {
  return (int) reader[name];
 }
 public static double GetDouble(this IDataReader reader, string name)
 {
  return (double) reader[name];
 }
 public static string GetString(this IDataReader reader, string name)
 {
  return (string) reader[name];
 }
 public static bool IsDBNull(this IDataReader reader, string name)
 {
  if (reader[name] == DBNull.Value)
   return true;

  return false;
 }
}

Since we didn't put our static class within a namespace, then our extension methods will be available at once. However, if you want to use a namespace, then you need to import the namespace in every class where you want to use these extension methods.