A buddy of mine and I were tossing around some ideas for scrubbing DBNull values so we could more easily grab values from a DataReader. Our first pass resulted with something like this:

T NullScrubber<T>(object checkValue) 
{
    T outValue;
    if (checkValue == DBNull.Value)
        outValue = default(T);
    else
        outValue = (T)checkValue;
    return outValue;
}

Basically, the NullScrubber method accepts am object value, since that is what the DataReader provides. Then it checks if the value is DBNull.Value. If it is, then ir returns that datatype’s default value. If not, it returns the value that was passed in. Either way, the value passed out is cast to the proper datatype.

You can test this with some code like this, which tests a null and non null value for 3 types:

object o1 = 123;
object o2 = DBNull.Value;
int x1 = NullScrubber<int>(o1);
int x2 = NullScrubber<int>(o2);
 
object o3 = "hello";
object o4 = DBNull.Value;
string x3 = NullScrubber<string>(o3);
string x4 = NullScrubber<string>(o4);
 
object o5 = true;
object o6 = DBNull.Value;
bool x5 = NullScrubber<bool>(o5);
bool x6 = NullScrubber<bool>(o6);
 

When applied to a DataReader usage, the o1 variable, for example, would be replaced with rdr[“UnitsInStock”]  

This works, and its a first pass … but I’d love to hear any thoughts/improvements anyone might have.

For you VB guys/gals, here is the VB version …

Private Function NullScrubber(Of T)(ByVal checkValue As Object) As T
    Dim outValue As T
    If checkValue Is DBNull.Value Then
        outValue = Nothing
    Else
        outValue = CType(checkValue, T)
    End If
    Return outValue
End Function

… and the VB test code …

Dim o1 As Object = 123
Dim o2 As Object = DBNull.Value
Dim x1 As Integer = NullScrubber(Of Integer)(o1)
Dim x2 As Integer = NullScrubber(Of Integer)(o2)
 
Dim o3 As Object = "hello"
Dim o4 As Object = DBNull.Value
Dim x3 As String = NullScrubber(Of String)(o3)
Dim x4 As String = NullScrubber(Of String)(o4)
 
Dim o5 As Object = True
Dim o6 As Object = DBNull.Value
Dim x5 As Boolean = NullScrubber(Of Boolean)(o5)
Dim x6 As Boolean = NullScrubber(Of Boolean)(o6)