C# Tips

C# Tip Article

Understanding DB NULL in C#

It is not unusual for C# developer to mix DBNull up with pure "null."
Take an example. If "state" column has NULL value, what is the return value?

SqlDataReader rs = cmd.ExecuteReader();
rs.Read();
object s = rs["state"];
if (s == null)
{    
	return false;
}
//...
return true;

It appears to be false but the correct answer is true since s is not "null."

When DB table column is NULL, DataReader returns a special type called System.DBNull.
System.DBNull is a empty class type that has bunch of methods and one static public field called "Value."
So in order to check that the column value is NULL, it should be compared with DBNull.Value as below.

object s = rs["state"];
if (s == DBNull.Value)
{
	return false;
}
//...
return true;

What if someone writes code like this?

object s = rs["state"];
if (s == null || s == DBNull.Value)
{
}

It is not wrong per se, but variable s will never be null, so "s == null" is unnecessary code.

One last thing. There is a method called Convert.IsDBNull() in .NET.
So we can also use this built-in method, which appears to me more clear.

object s = rs["state"];
if (Convert.IsDBNull(s))
{
}