SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

January 18, 2010

C# Extension Methods for IDataReader

My team often starts Tuesday morning status meetings with a round of win/learn/fun - a team-building exercise where each person gets to mention an exciting "win", something they learned in the last week, or just something fun. Several weeks ago someone brought up C# Extension Methods as a learn. I could see the potential, but I didn't immediately think of any practical examples.

Fast forward: working on an application at home, and started the data layer. I was reminded that I am annoyed the fact that IDataReader does not have a GetString(colName: string) method (or other data types). Instead, you must use reader.GetString(reader.GetOrdinal(colName)). And you must watch out for null values. Suddenly struck me that this would be a good candidate for an extension method. So I created the following:

public static class IDataReaderExtensions
{
     public static string GetStringFromName(this IDataReader reader, string colName)
     {
          string value = string.Empty;
          if (!reader.IsDBNull(reader.GetOrdinal(colName)))
          {
               value = reader.GetString(reader.GetOrdinal(colName));
          }
          return value;
     }
}

Note that I have purposefully chosen to use empty strings instead of nulls, because that is the appropriate response for this domain. I also chose to name the function GetStringFromName because I prefer avoiding the confusion of having the same name as a fundamental method on the interface. Finally, use the function: add using directive for the namespace, and then string colValue = reader.GetStringFromName(colName);. Now I just need to spend a few minutes creating similar methods for the other data types. Optionally I could add in custom error handling for situations where the column does not exist, or the reader does not have any data, etc.

TrackBack

Comments

Post a comment

Remember personal info?




deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there