Correct way to check if a type is Nullable

C#GenericsNullable

C# Problem Overview


In order to check if a Type ( propertyType ) is nullable, I'm using:

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

Is there some way that avoid using magic strings ?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Use the following code to determine whether a Type object represents a Nullable type. Remember that this code always returns false if the Type object was returned from a call to GetType.

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

explained at the below MSDN link:

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

Moreover, there is a similar discussion at this SO QA:

How to check if an object is nullable?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFelice PollanoView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#VSSView Answer on Stackoverflow