Coder Perfect

How to check if a type is nullable the right way [duplicate]

Problem

I’m using the following code to see if a Type (propertyType) is nullable:

bool isNullable =  "Nullable`1".Equals(propertyType.Name)

Is there a way to prevent having to use magic strings?

Asked by Felice Pollano

Solution #1

Nullable is the way to go. GetUnderlyingType:

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

It’s worth noting that this uses the System static class, which isn’t generic. Rather using the generic struct NullableT>, use Nullable.

Also, keep in mind that this will only work if you use it on a specific (closed) nullable value type… it won’t work if you use it on a generic type, such as a string.

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...

Answered by Jon Skeet

Solution #2

To see if a Type object represents a Nullable type, run the following code. Remember that if the Type object was returned through a GetType call, this code always returns false.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

explained in the MSDN link below:

http://msdn.microsoft.com/en-us/library/ms366789.aspx

Furthermore, this SO QA has a similar discussion:

What is the best way to see if an object is nullable?

Answered by VSS

Post is based on https://stackoverflow.com/questions/8939939/correct-way-to-check-if-a-type-is-nullable