How do I convert a System.Type to its nullable version?
.net, c#
Solution
Here is the code I use:
Type GetNullableType(Type type) {
// Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
if (type.IsValueType)
return typeof(Nullable<>).MakeGenericType(type);
else
return type;
}
Problem
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, but how do I get the nullable version of a .NET type? So I have ``` typeof(int) typeof(DateTime) System.Type t = something; ``` and I want ``` int? DateTime? ``` or ``` Nullable<int> (which is the same) if (t is primitive) then Nullable<T> else just T ``` Is there a built-in method?