posted on Saturday, May 14, 2005 5:00 PM by Saravana

Custom CheckDBNull function in Whidbey using Generics.

In .NET 1.x, most of you would have created a utility function for doing the following two things

  • Check for dbnull 
  • Typecast the value to required data type or return the default value in case of dbnull. 

For example,     

// return default value for integer if the object is null

            public int DBCheckforInt(object i)

            {

                  if (i == System.DBNull.Value)

                        return 0;

                  else

                        return (int)i;

            }

 

            // return default value for decimal if the object is null

            public double DBCheckfordouble(object o)

            {

                  if (o == System.DBNull.Value)

                        return 0.0;

                  else

                        return (double)o;

            }

 

Note: For performance reason, you need to use System.DBNull.Value instead of using IsDBNull() function to check for dbnull. More details here.

Major disadvantage with this approach is, we need to create a function for each datatype that we require to check for dbnull. However, the logic is same for all the datatype. In whidbey, generics helps us to solve this kind of problem i.e. you can can pass data type as parameter to that function. In that function depending upon the datatype, return the default value for that datatype or typecast and return the value.  For example, same utility function in whidbey will be

 

public static T DBNullCheck<T>(Object obj)

            {

                  return obj == System.DBNull.Value ? default(T) : (T)obj;

            }

 

In whidbey, it is one function for all the data types. default is the keyword in whidbey returns the default value for the specified datatype.  To know more about genercis, check out these articles on generics,

    1. CLR and Language Enhancements in Whidbey
    2. Generics Internals

One problem with this method is, for String it returns default value as null. In some cases, we might have String.Empty as default value for String. In those cases, this method might not be useful. But for all other primitive data types, this method will work.

 

Comments