Search code examples
.netsqlstringnulldbnull

Confused about null strings and DBNull


I'm looking at some code for a .net program I'm working on. The previous author of the program gave the code to me over a year ago. Suddenly, I am seeing an exception thrown from code that I haven't touched:

if ((string)row["LevelName"] != "ABC")

The exception is "Unable to cast object of type 'System.DBNull' to type 'System.String'.

I thought that string was a nullable data type, so how can I possibly be getting this exception?


Solution

  • DBNull is it's own class, which contains a singleton instance of itsself in a property called Value. DBNull.Value is not equal to null, as it is a reference to an instance of this class.

    Most, if not all database wrappers will return DBNull.Value instead of null when there is no value. One of the reasons for this is because returning a real null could mean there is no row at all, not just a null value in the column (it depends on what objects you're using to get the values though).

    Generally, the as operator is very usefull with DBNull and can be used with any nullable type (including string).

    string str = reader["Name"] as string;
    int? i = reader["Age"] as int?;
    

    It might also be worth mentioning that the ?? operator is very usefull here too, when you need a non-nullable value type (although it doesn't look too pretty).

    int i = reader["Age"] as int? ?? -1;
    

    I find this very handy as a little just-in-case scenario in a LINQ select clause.