Search code examples
c#nullable

Are these tests for Nullable Type equivalent?


Here is the condition I used to detect if we are dealing with a Nullable Type :

System.Nullable.GetUnderlyingType(itemType) != null

and here the code of my teammate :

itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(Nullable<>)

We actually didnt find a case where one will return true and the other false (or vice-versa) but are these 2 snippets strictly equivalent ?


Solution

  • From MSDN for Nullable.GetUnderlyingType Method:

    The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null.

    So, yes it is safe to use the former version.

    Decompiled from GetUnderlyingType:

    public static Type GetUnderlyingType(Type nullableType)
    {
      if (nullableType == null)
        throw new ArgumentNullException("nullableType");
      Type type = (Type) null;
      if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition && nullableType.GetGenericTypeDefinition() == typeof (Nullable<>))
        type = nullableType.GetGenericArguments()[0];
      return type;
    }