Skip to content

Commit

Permalink
Use NullabilityInfoContext to determine dictionary nullability (#3041)
Browse files Browse the repository at this point in the history
Use `NullabilityInfoContext` to determine dictionary type nullability correctly.
  • Loading branch information
patrikwlund authored Aug 24, 2024
1 parent 7a7230d commit 31ad99f
Show file tree
Hide file tree
Showing 3 changed files with 257 additions and 44 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,23 @@ public static bool IsNonNullableReferenceType(this MemberInfo memberInfo)

public static bool IsDictionaryValueNonNullable(this MemberInfo memberInfo)
{
#if NET6_0_OR_GREATER
var context = new NullabilityInfoContext();
var nullableInfo = memberInfo.MemberType == MemberTypes.Field
? context.Create((FieldInfo)memberInfo)
: context.Create((PropertyInfo)memberInfo);

if (nullableInfo.GenericTypeArguments.Length != 2)
{
var length = nullableInfo.GenericTypeArguments.Length;
var type = nullableInfo.Type.FullName;
var container = memberInfo.DeclaringType.FullName;
var member = memberInfo.Name;
throw new InvalidOperationException($"Expected Dictionary to have two generic type arguments but it had {length}. Member: {container}.{member} Type: {type}.");
}

return nullableInfo.GenericTypeArguments[1].ReadState == NullabilityState.NotNull;
#else
var memberType = memberInfo.MemberType == MemberTypes.Field
? ((FieldInfo)memberInfo).FieldType
: ((PropertyInfo)memberInfo).PropertyType;
Expand Down Expand Up @@ -104,6 +121,7 @@ public static bool IsDictionaryValueNonNullable(this MemberInfo memberInfo)
}

return false;
#endif
}

private static object GetNullableAttribute(this MemberInfo memberInfo)
Expand Down
Loading

0 comments on commit 31ad99f

Please sign in to comment.