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!
The analysis is trying to learn from your usage of the value. Consider this recently annotated (and presumably incorrectly annotated) code:
Here the
nulltest is telling the analysis that you think the value could be null, even though the incoming reference type isstringnotstring?.It's the same in your code. The
?.Countis 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.