Search code examples
.netsqldbnull

Most efficient way of dealing with DBNull in .NET


Possible Duplicate:
What is the best way to deal with DBNull's

What is the most efficient syntax in .NET to set a variable that has a value of DBNull (aka SQL null value being returned)? I remember reading something that was put into .NET 3.0 for this sort of thing. Lets assume the variable I'm setting has a type of DateTime.

Common error:
Conversion from type 'DBNull' to type 'Date' is not valid.


Solution

  • DateTime is a value type, and can only contain valid date/times. Typically the way this is handled is to check your value returned from teh database to see if it's DBNull.Value, and if so set the DateTime to a special value like DateTime.MinValue which represents Null.

    Alternatively you can use DateTime? which is a nullable DateTime datatype and you can actually assign it null (regular .Net null, not DBNull).

    DateTime foo;
    if (row["SomeField"] == DBNull.Value) {
        foo = DateTime.MinValue;
    } else {
        foo = (DateTime)row["SomeField"];
    }
    

    You can make this syntax a little bit nicer by creating an extension method on a DataRow like so:

    public static void ToDateTime(this DataRow row, string columnName) {
        if (row[columnName] == DBNull.Value) {
            return DateTime.MinValue;
        } else {
            return (DateTime)row[columnName];
        }
    }
    

    then you can rewrite the original code like this:

    DateTime foo = row.ToDateTime("SomeField");