Friday, November 4, 2011

Generic Method For Converting From DBNull

public static T FromDB<T>(object o)
{
   return o is DBNull ? default(T) : (T)o;
}

The method above is written in C# using generics. This method is used to cast weakly typed objects returned from a DataRow to strongly typed objects and it will automatically handle the conversion of DBNull. This method can also be used with nullable types which is convenient since capturing null values is often important when querying databases.

Below is a full example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            object i1 = 7;
            object i2 = DBNull.Value;
            object i3 = 3;
            object i4 = DBNull.Value;
            object i5 = "TEST";
            object i6 = DBNull.Value;

            int o1 = FromDB<int>(i1);
            int o2 = FromDB<int>(i2);
            int? o3 = FromDB<int?>(i3);
            int? o4 = FromDB<int?>(i4);
            string o5 = FromDB<string>(i5);
            string o6 = FromDB<string>(i6);

            Console.WriteLine("o1 = {0}", o1); //can't be null since its value type
            Console.WriteLine("o2 = {0}", o2); //can't be null since its value type
            Console.WriteLine("o3 = {0} {1}", o3, o3 == null ? "(NULL)" : "");
            Console.WriteLine("o4 = {0} {1}", o4, o4 == null ? "(NULL)" : "");
            Console.WriteLine("o5 = {0} {1}", o5, o5 == null ? "(NULL)" : "");
            Console.WriteLine("o6 = {0} {1}", o6, o6 == null ? "(NULL)" : "");
        }

        public static T FromDB<T>(object o)
        {
            return o is DBNull ? default(T) : (T)o;
        }
    }
}

The output would be:

o1 = 7
o2 = 0
o3 = 3
o4 = (NULL)
o5 = TEST
o6 = (NULL)