Who needs DBNull?
I’m currently taking part in my first MS certified .NET training. I’ll write some more about this training after it’s over, but now I have to share one thing with you. Once again I notices that DBNull is causing more confusion than it is worth. A certified .NET instructor had a hard time describing it to course attendees. Some time ago I had a long conversation about it. Both time I couldn’t help my self thinking: “who to hell needs this DBNull”. Because in .NET DBNull is not equal null. DBNull is a little extraordinary data type. It is used to describe a value from DB that does not exists in opposition to a value that exists but is null. Hmm… I don’t buy it. And a course attendee was not buying it also. We have defined a class like this
public sealed class ProductSummaryStatistics { private readonly string mDescription; private readonly int mProductCount; private readonly decimal? mMinimumPrice; private readonly decimal? mMaximumPrice; private readonly decimal? mAveragePrice; //... }
We ware told what the nullable types are. I had BTW impression that our trainer was not 100% clear about the difference between value and reference types, since with that knowledge the difference between decimal and decimal? is crystal clear in a second.
But back to our story. We were told to use a helper method co convert the “may by null” values to the fields in our class. That’s the helper code:
public static Nullable<T> DbValueToNullable<T>(object dbValue) where T : struct { Nullable<T> returnValue = null; if ((dbValue != null) && (dbValue != DBNull.Value)) { returnValue = (T)dbValue; } return returnValue; }
My coulage could not understand why do we have to convert our DB data that might by null to nullable type. And to by frank I don’t understand neither. And it is really not important that my lack of understanding is other than my colleague. We don’t need DBNull!