Search code examples
c#.netnullable-reference-types

Why is there 'dereference of possible null exception' warning when null check result is assigned to variable?


Working on enabling the feature to treat nullable warnings as errors and I am running into scenarios like below where I am getting CS8602: Dereference of possibly null reference warning.

List<string>? a = null;
var wasCreated = a != null;
//if (a != null) // using this doesnt give the warning
if (wasCreated) // using this gives the warning
{
    a.Add("b"); // Warning happens here.
}

Reading through the docs I didn't see any explicit statement calling out assigning null check result in variable and checking variable would not suffice. Is the compiler really incapable of identifying null check has happened when done that way?


Solution

  • This is a known limitation of current compiler. Introducing an intermediate variable will "break" the nullable flow analysis since compiler does not perform any kind of alias/value tracking in this case (due to potential cost in both performance and implementation as far as I understand).

    From this github comment:

    Closing as we've decided not to do this type of dependent/alias flow analysis in the compiler.

    Or this one:

    This is essentially asking for nullable to support alias tracking. That is a feature we've explicitly decided to not do in 8.0 due to the complexity. I have some doubts we'd ever be able to do it because of the inherent complexity of alias tracking in C#.
    Primary bug tracking this is #34644. Yes that is about indexers but it's the same fundamental problem: alias/value tracking.

    And several others similar - one, two, three. Also this commend about "path-independent flow analysis" is related too as far as I understand.