Database Safe Values, Using Generics, and Extension Methods

In my early years as a Developer I was using DotNetNuke and often had large Data Access Layers (DALs) to abstract the database away from my application. I quickly found myself checking to ensure that a value returning from the Database wasn’t NULL (\0), so I created a helper class that had a number of methods for each data type I interacted with.  This created was done similar to this code below:

 public static double ConvertNullDoubleobject field)
 {
       if (field != DBNull.Value)
           return Convert.ToDouble(field);
       return 0; // or if my application had Defaults Global.DefaultDouble
 }

This seemed like a great solution at the time, but is quite a lot of code, as you are writing a method for every…single…datatype that your application interacts with. Being in a Small Business you didn’t really get the ability to refactor code that often, so once it was written you stuck by it.

Moving along in my career I stepped into Environment that already had full DALs in place so I would mimic what the previous developer did in order to keep the code base easily maintainable, as there is never a lack of fun trying to understand more than one persons point of view across a piece of code.

Tonight I was scanning through twitter and noticed Ben Alabaster [@BenAlabaster] asking a quite a unique question on twitter. So I piped in with my two cents, and then the conversation sparked beyond twitter to msn, then eventually to Skype. Here is the unique Single Helper Method we came up with:

For .NET 2.0, a static method:

public static T ConvertDBNullToSafeOrDefaultTypeValue<T>(object field)
{
      if (field != DBNull.Value)
          return (T)Convert.ChangeType(field, typeof(T));
      return default(T);
}

For .NET 3.5, an Extension method:

public static T ConvertDBNullToSafeOrDefaultTypeValue<T>(this object field)
{
      if (field != DBNull.Value)
           return (T)Convert.ChangeType(field, typeof(T));
      return default(T);
}

This solution provides a source code friendlier way of returning values from a database and validating the data against your business rules [you can replace default(T) is a Generic way of handling your applications default values].

Happy Coding!