Why does [ContractAnnotation] not work in a nullable context?

60 Views Asked by At

I have currently the following situation which is working perfectly using vanilla Jetbrains.Annotations and with disabled nullable annotations.

#nullable disable
[ContractAnnotation("parameter:null => notnull")]
[CanBeNull]
string Check([CanBeNull] string parameter)
{
  return parameter == null ? "ParameterIsNull" : null;
}

void Foo([CanBeNull] string value)
{
  if (Check(value) is null) {
    // no warning -> CORRECT
    var length = value.Length;
  }
  else {
    // WARNING: Possible NullableReferenceException -> CORRECT
    var length2 = value.Length;
  }
}

But when I activate the nullable annotations, my IDE suggests me to use type annotations. As a result, a possible NullableReferenceException warning is shown, which is simply invalid.

#nullable enable
[ContractAnnotation("parameter:null => notnull")]
string? Check(string? parameter)
{
  return parameter == null ? "ParameterIsNull" : null;
}
void Foo(string? value)
{
  if (Check(value) is null) {
    // WARNING: Possible NullableReferenceException -> WRONG!!!
    var length = value.Length;
  }
  else {
    // WARNING: Possible NullableReferenceException -> CORRECT
    var length2 = value.Length;
  }
}

I've tried to find some appropriate annotations, but only found the following:

  • AllowNull
  • DisallowNull
  • MaybeNull
  • NotNull
  • MaybeNullWhen
  • NotNullWhen
  • NotNullIfNotNull
  • MemberNotNull
  • MemberNotNullWhen
  • DoesNotReturn
  • DoesNotReturnIf

I would require a [NotNullIfNull] on the "parameter" or similar?

0

There are 0 best solutions below