Jun 232011

Duty of every decent Data Access Layer is to convert data types that we have in database to data types of our favorite programming language (C# in this case). And this is easy in case of “normal” data types. Great example here is humble integer. Database and C# have 1 to 1 mapping here. It is as easy as “var x = (int)dr["field"];“.

However, database can have one more trick up it’s sleeve. Every data type can be “nullable”. That is, it can be integer but it can also have special state which signifies lack of data. C# also has same possibility with his nullable types. Intuitive code “var x = (int?)dr["field"];” will not work properly.

While we can make wrapper function for any nullable data type that we need, there is simpler way. All that we need is:

private static Nullable<T> ToNullable<T>(object value) where T : struct {
    if (value == null) { return null; }
    if (System.Convert.IsDBNull(value)) { return null; }
    return (T)value;

Now conversion can proceed with “var x = ToNullable(dr["field"]);“. That doesn’t look that ugly, does it?

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>