Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a non-nullable type to a nullable type?

Is it possible to convert a non-nullable value type known only at runtime to nullable? In other words:

public Type GetNullableType(Type t)
{
    if (t.IsValueType)
    {
        return typeof(Nullable<t>);
    }
    else
    {
        throw new ArgumentException();
    }
}

Obviously the return line gives an error. Is there a way to do this? The Type.MakeGenericType method seems promising, but I have no idea how to get a unspecified generic Type object representing Nullable<T>. Any ideas?

like image 276
jjoelson Avatar asked Oct 20 '11 13:10

jjoelson


3 Answers

you want typeof(Nullable<>).MakeGenericType(t)

Note: Nullable<> without any supplied arguments is the unbound generic type; for more complex examples, you would add commas to suit - i.e. KeyValuePair<,>, Tuple<,,,> etc.

like image 86
Marc Gravell Avatar answered Oct 13 '22 11:10

Marc Gravell


You're on the right track. Try this:

if (t.IsValueType)
{
    return typeof(Nullable<>).MakeGenericType(t);
}
else
{
    throw new ArgumentException();
}
like image 23
Adam Robinson Avatar answered Oct 13 '22 11:10

Adam Robinson


Type GetNullableType(Type type) {
    // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper
    // if type is already nullable.
    type = Nullable.GetUnderlyingType(type);
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);
    else
        return type;
} 
like image 37
ratneshsinghparihar Avatar answered Oct 13 '22 09:10

ratneshsinghparihar