Identifying if a type is nullable and getting its underlying (not nullable) type is something no one needs constantly but when we do it’s not trivial to get just from intellisense.

There is no IsNullable property in System.Type so we need to understand a bit how thing work.

Type myType = (Guid?).GetType(); // dummy type for this example

For short:

Type myBaseType = Nullable.GetUnderlyingType(myType) ?? myType;

If you need a bit more information:

myType.IsGenericType();
myType.GetGenericTypeDefinition() == typeof(Nullable<>)  
myType.GetGenericArguments()[0]

The Long story:

The basic idea of a nullable type is that it is a type wrapped in the generic type NULLABLE<>.
So to know if a type is nullable we need to:

  • Evaluate if the type is generic
  • Being generic, lets check if it's Nullable<>
  • If so, get its first generic argument that holds the base type.
    • If you run a QuickWatch on a nullable Guid? type you'll get something like:
      System.Nullable`1[System.Guid]
      System.Nullable`1[] is the way .net serializes NULLABLE<>
      The value within [] is its undelying type we're looking for.