Handling DBNull in C#

Let's talk about DBNull today.

DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.

Ex

if (! DBNull.Value.Equals(row[fieldName]))
return (string) row[fieldName] + " ";
else
return String.Empty;
 

Please do not confuse the notion of null in C# language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object, whereas DBNull represents an uninitialized field or nonexistent database column.

Below is one way to abstract the DBNull implementation and return null to middle/front end of the Data layer.

SqlDataReader r = ...;

String firstName = getString(r[COL_Firstname]);

private static string getString(object o)

{

    if (o == DBNull.Value) return null;

    return (string) o;

}
 

References: MSDN and stack overflow