Home > Blockchain >  Why is the .NET null conditional operator not returning false when trying to check if a collection h
Why is the .NET null conditional operator not returning false when trying to check if a collection h

Time:05-17

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 :(

CodePudding user response:

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()) { ... }

CodePudding user response:

null doesn't equal false, nor does null equal true. The simple way to fix this is to check if the result of ?.Any() isn't true (ie null or false).

if (result?.Pets?.Any() != true) { ... }
  • Related