Search code examples
c#nullable-reference-typesnull-conditional-operator

Why using null-conditional operator in nullable context breaks static analyzer?


Why after using null-conditional-operator in nullable context (#nullable enable ) the static analyzer shows CS8602 warning?

var test = new List<int>();

Console.WriteLine(test.Count); // Ok
Console.WriteLine(test?.Count);
Console.WriteLine(test.Count); // CS8602 - Dereference of a possibly null reference

Here is fiddle.

Is the answer simply "not smart enough"? I don't know how could test become null after ?., can it?


Another thought, there is actually a missing warning:

Remove unnecessary null-conditional check, test can NOT BE be null here! Don't you see? Read tooltips! On every variable!


Solution

  • The analysis is trying to learn from your usage of the value. Consider this recently annotated (and presumably incorrectly annotated) code:

    #nullable enable
    public int M(string s)
    {
        int i = 0;
        if (s is null)
            i++;
        i += s.Length; // possible NullReferenceException!
        return i;
    }
    

    Here the null test is telling the analysis that you think the value could be null, even though the incoming reference type is string not string?.

    It's the same in your code. The ?.Count is a null check, which makes the code afterwards think the value could be null.

    Looking at your example, it's obvious that it could never be null. Clearly the analysis could be taught to differentiate between our two examples.

    This feels like something that would have been discussed on https://github.com/dotnet/roslyn or https://github.com/dotnet/csharplang. If not, you could open an issue there to suggest an improvement to the compiler's analysis.