csharpsquid:S1168 should not apply for explicitly nullable return types

Sonar version: 9.9 (build 65466)

This is not strictly a false positive, but I think rule 1168 should not apply if the return type of the function is explicitly nullable (see nullable reference types, introduced in C# 8.0).

Oftentimes when I write code which returns a nullable collection I mean to treat the result as a single object for which being a collection is not the feature I am interested in. In any case I think the explicit nullable declaration should be enough of an opt-out.

Some concrete examples include files treated as units (byte[]) or the several objects in the Open XML SDK which implement IEnumerable<OpenXmlElement>.

byte[]? TryGetFile(string fileName)
{
    return File.Exists(fileName)
        ? File.ReadAllBytes(fileName)
        : null;
}
1 Like

I agree with this. I created a (draft) PR: FIX S1168: FP should not apply for explicitly nullable return types by Corniel · Pull Request #6952 · SonarSource/sonar-dotnet · GitHub

I hope the outstanding issue can be solved easily, but how to do that is not up to me.

1 Like

Thank you @m-gallesio for reporting this. This is a known issue and you can track our work on this here Fix S1168 FP: Does not respect nullable annotations · Issue #6878 · SonarSource/sonar-dotnet · GitHub.

1 Like

@m-gallesio The PR has been merged today. So, with the next, this feature should be available.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.