Correct way to check if a type is Nullable [duplicate]

Absolutely – use Nullable.GetUnderlyingType:

if (Nullable.GetUnderlyingType(propertyType) != null)
{
    // It's nullable
}

Note that this uses the non-generic static class System.Nullable rather than the generic struct Nullable<T>.

Also note that that will check whether it represents a specific (closed) nullable value type… it won’t work if you use it on a generic type, e.g.

public class Foo<T> where T : struct
{
    public Nullable<T> Bar { get; set; }
}

Type propertyType = typeof(Foo<>).GetProperty("Bar").PropertyType;
// propertyType is an *open* type...

Leave a Comment