roslyn: Possible bug in the flow analysis of nullable reference types
I’ve just enabled the new nullable reference types feature.
In this example, myObj
is nullable. But shouldn’t the compiler understand that myObj won’t be null in this case, since I’m testing for it in the if clause?
I’m using .NET Core 3.0 in VS 2019.
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Comments: 17 (9 by maintainers)
Commits related to this issue
- Close issue #39424 — committed to jcouv/roslyn by jcouv 4 years ago
It should, but the compiler cannot infer everything. In 8.0 it recognizes the most common null-check patterns only. Does the warning go away if you replace the test with
myObj != null && myObj.HasChanged
?Also, I think this should be in dotnet/roslyn, since C# spec doesn’t mention which null check patterns must be recognized.
Relates to discussion at https://github.com/dotnet/csharplang/issues/2764
I still don’t think it makes sense to pinpoint to such “patterns” inside the compiler, this is a byproduct of how flow analysis works. Ideally, it should be extended in a general manner to understand always-true/false/null/not null in a broader context.
R# has done a good job to infer such states in the local scope even when the code is not annotated at all.
I agree that this is a pattern that the language/compiler should likely support.
I can [eproduce the warning using SharpLab.
Changing the condition from
?? false
to== true
has the same semantics, and doesn’t generate a warning.You can report this on Roslyn, and they may choose to add support for this pattern.