Search code examples
c#.netnull-conditional-operator

Why is the .NET null conditional operator not returning false when trying to check if a collection has any items?


I'm trying to do the following check:

if (result?.Pets?.Any() == false) { ... }

and if result == null .. then it's not going inside the scope of that if check.

I thought that result?. will (in this case) return null .. so is this then trying to do:

if (null == false) { ... } // result == null

and if that is the case .. then what? My first thought was something like this:

if (result?.Pets?.Any() == false ?? false) { .. } 

but that is a compiler error :(


Solution

  • As others have explained, null does not equal false. Using the null-coalescing operator ?? to get around this should work but your syntax is incorrect. The correct syntax would be something like this:

    if ((result?.Pets?.Any() ?? false) == false) { ... }
    

    However, for readability, I would go for something like this:

    bool petsFound = result?.Pets?.Any() ?? false;
    if (!petsFound) { ... }
    

    Alternatively, you could do it the good old way using a null check and the short-circuiting || operator:

    if (result?.Pets is null || !result.Pets.Any()) { ... }