How to: Identify a nullable type (C# Programming Guide)

The following example shows how to determine whether a System.Type instance represents a closed generic nullable type, that is, the System.Nullable<T> type with a specified type parameter T:

Console.WriteLine($"int? is {(IsNullable(typeof(int?)) ? "nullable" : "non nullable")} type");
Console.WriteLine($"int is {(IsNullable(typeof(int)) ? "nullable" : "non nullable")} type");

bool IsNullable(Type type) => Nullable.GetUnderlyingType(type) != null;

// Output:
// int? is nullable type
// int is non nullable type

As the example shows, you use the typeof operator to create a System.Type object.

If you want to determine whether an instance is of a nullable type, don't use the Object.GetType method to get a Type instance to be tested with the preceding code. When you call the Object.GetType method on an instance of a nullable type, the instance is boxed to Object. As boxing of a non-null instance of a nullable type is equivalent to boxing of a value of the underlying type, GetType returns a Type object that represents the underlying type of a nullable type:

int? a = 17;
Type typeOfA = a.GetType();
Console.WriteLine(typeOfA.FullName);
// Output:
// System.Int32

Don't use the is operator to determine whether an instance is of a nullable type. As the following example shows, you cannot distinguish types of instances of a nullable type and its underlying type with using the is operator:

int? a = 14;
if (a is int)
{
    Console.WriteLine("int? instance is compatible with int");
}

int b = 17;
if (b is int?)
{
    Console.WriteLine("int instance is compatible with int?");
}
// Output:
// int? instance is compatible with int
// int instance is compatible with int?

You can use the code presented in the following example to determine whether an instance is of a nullable type:

int? a = 14;
int b = 17;
if (IsOfNullableType(a) && !IsOfNullableType(b))
{
    Console.WriteLine("int? a is of a nullable type, while int b -- not");
}

bool IsOfNullableType<T>(T o)
{
    var type = typeof(T);
    return Nullable.GetUnderlyingType(type) != null;
}

// Output:
// int? a is of a nullable type, while int b -- not

See also