Search code examples
c#reflectionnullable-reference-types

Determine if a reference type is nullable at runtime


In C# it's trivial to determine whether a value type is nullable. Specifically, you can obtain this information from the Type itself; for example:

public static bool IsNullable(this Type type) =>
    type.IsValueType && Nullable.GetUnderlyingType(type) is not null;

As I understand, it's possible to obtain nullability information for nullable reference types via NullableAttribute or NullableContextAttribute, but it would appear that this has to be obtained from MemberInfo, rather than from the Type.

Is this understanding correct, or is there a workaround to obtain nullability information for nullable reference types from a Type?


Solution

  • Nullable reference types (C# reference):

    Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.

    That's the reason why you can't use typeof on a nullable reference type:

    Type t = typeof(string?); // error CS8639
    

    So you need a PropertyInfo or FieldInfo if you want to check if it's nullable, for example:

    public static bool IsMarkedAsNullable(PropertyInfo p)
    {
        return new NullabilityInfoContext().Create(p).WriteState is NullabilityState.Nullable;
    }
    

    Copied extension from here: How to use .NET reflection to check for nullable reference type