Once again one of those: \"Is there an easier built-in way of doing things instead of my helper method?\"
So it\'s easy to get the underlying type from a nullable type,
Lyman's answer is great and has helped me, however, there's one more bug which needs to be fixed.
Nullable.GetUnderlyingType(type)
should only be called iff the type isn't already a Nullable
type. Otherwise, it seems to erroneously return null when the type derives from System.RuntimeType
(such as when I pass in typeof(System.Int32)
). The below version avoids needing to call Nullable.GetUnderlyingType(type)
by checking if the type is Nullable
instead.
Below you'll find an ExtensionMethod
version of this method which will immediately return the type unless it's a ValueType
that's not already Nullable
.
Type NullableVersion(this Type sourceType)
{
if(sourceType == null)
{
// Throw System.ArgumentNullException or return null, your preference
}
else if(sourceType == typeof(void))
{ // Special Handling - known cases where Exceptions would be thrown
return null; // There is no Nullable version of void
}
return !sourceType.IsValueType
|| (sourceType.IsGenericType
&& sourceType.GetGenericTypeDefinition() == typeof(Nullable<>) )
? sourceType
: typeof(Nullable<>).MakeGenericType(sourceType);
}
(I'm sorry, but I couldn't simply post a comment to Lyman's answer because I was new and didn't have enough rep yet.)