Efficiently handling DBNull in C#

Hello friends,

Let’s go through 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;

}

Hope you found this post useful. Please share your comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *