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?
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.
You're on the right track. Try this:
if (t.IsValueType)
{
return typeof(Nullable<>).MakeGenericType(t);
}
else
{
throw new ArgumentException();
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With