How to check if an object is nullable?

There are two types of nullable – Nullable<T> and reference-type.

Jon has corrected me that it is hard to get type if boxed, but you can with generics:
– so how about below. This is actually testing type T, but using the obj parameter purely for generic type inference (to make it easy to call) – it would work almost identically without the obj param, though.

static bool IsNullable<T>(T obj)
{
    if (obj == null) return true; // obvious
    Type type = typeof(T);
    if (!type.IsValueType) return true; // ref-type
    if (Nullable.GetUnderlyingType(type) != null) return true; // Nullable<T>
    return false; // value-type
}

But this won’t work so well if you have already boxed the value to an object variable.

Microsoft documentation: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/how-to-identify-a-nullable-type

Leave a Comment