How to easily deal with Nullable Types
If you have to work with mapping data to objects you know what a pain working with nulls has been historically. In the past, your database can deal with nulls very easy but your object model could not. As developers and architects, we would have to come up with “schemes” to deal with a null. It was a total pain in the aspirin bottle. Now, with the Nullable Types in .NET, it is much better situation, though it is still a bit tricky when dealing with Nullable Types and generics. The two tricky things that I need to mess with are knowing if a type is “nullable” and what the heck is the “underlying” type so I can do type conversions (mainly for DLINQ expression building.) So here is some code that may help.
If you need to know if a type is Nullable or not:
bool IsNullableType(Type theType)
{
return (theType.IsGenericType && theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
}
You will find in DLINQ when creating dynamic expressions, that you may need to convert types, and often they are nullable.
Converting to the underlying type:
// UnderlyingType will equal System.DateTime
var nc = new System.ComponentModel.NullableConverter(Nullable<DateTime>);
Type underlyingType = nc.UnderlyingType;
Note: I totally stole this info from David Hayden because, as you know, plagiarism is the most sincere form of flattery.