To check if a value type is nullable I'm currently doing something like this:
int? i = null;
bool isNullable = i.GetType().ToString().Contains("System.Nullable");
Is there a more elegant way to do this?
To check if a value type is nullable I'm currently doing something like this:
int? i = null;
bool isNullable = i.GetType().ToString().Contains("System.Nullable");
Is there a more elegant way to do this?
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// it is a nullable type
}
This is how Microsoft recommends you Identify Nullable Types
int? i;
bool isNullable = i is Nullable;
Edit: Nevermind, this doesn't work.
You can use Nullable.GetUnderlyingType(Type)
- that will return null
if it's not a nullable type to start with, or the underlying value type otherwise:
if (Nullable.GetUnderlyingType(t) != null)
{
// Yup, t is a nullable value type
}
Note that this uses the Nullable
static class, rather than the Nullable<T>
structure.