Jonas Stawski

Everything .NET and More

Generic IsNull Helper Method

When you use DataReaders you have to check for DBNull.Value on every field that could have a possible null value to make sure you don't get an exception. Therefore your code ends up having a lot of these:

if (dr["Colunm1"] != DBNull.Value)
    SomeStringVariable = dr["Column1"].ToString();
 
//or using inline if
 
SomeStringVariable = (dr["Column1"] != DBNull.Value ? dr["Column1"].ToString() : String.Empty);
If dr("Column1") is DBNull.Value Then
    SomeStringValue = dr("Column1").ToString()
End If

The other day I got tired of it so I decided to take advantage of Generics and write a generic method:

private static T IsNull<T>(object o) 
{ 
    T retValue = default(T); 
    if (o != DBNull.Value) { 
        retValue = (T)o; 
    } 
    
    return retValue; 
} 
Private Shared Function IsNull(Of T)(ByVal o As Object) As T
    Dim retValue As T = Nothing
    If o IsNot DBNull.Value Then
        retValue = CType(o, T)
    End If
 
    Return retValue
End Function

You then use this method like this:

IntVariable = IsNull<int>(dr["IntColumn"]); 
StringVariable = IsNull<string>(dr["StringColumn"]); 
IntVariable = IsNull(Of Integer)(dr("IntColumn"))
StringVariable = IsNull(Of String)(dr("StringColumn"))

Of course you can use any type you need.

Happy programming!

Comments (1) -

Jose Rodriguez
Jose Rodriguez

Simple yet so powerful. Thanks for posting this...you saved me 20 minutes. That said, I need to delve more into Generics. Lots of good stuff in there. Cheers!

Reply

Add comment

biuquote
Loading