Can someone please explain the logic of the null-conditional operator in if statements?
Imagine the following code
List<string> items = null;
if (items?.Count == 0)
{
Console.WriteLine("error");
}
else
{
Console.WriteLine("OK");
}
The above will print OK. Why does it compile when the next block would not?
if (items?.Any()) // won't compile but if (items?.Count() == 0) would
{
...
}
I am guessing the ?. will stop execution when null detected and the entire if is skipped but why is it not the case with "?.Any()"? Just because it's a method whereas "count" is a property?
And why does the Linq extension method Any() require an explicit conversion from Nullable to bool where Count() == 0 compiles with no conversion Nullable to int required?
if items is null, then items?.Count is null, too.
and null == 0 is a comparison that results in false. so the if is happy.
but items?.Any() will also be null - and if(null) is invalid, because null is not a boolean, and cannot be converted to one.
so you simply have to provide a fallback boolean value:
if (items?.Any() ?? false) {
}
will do the trick
Consider the null case.
In if (items?.Count == 0) that becomes if (null == 0) and that gives false.
But in if (items?.Any()) it becomes if (null) and that is invalid.
You can use if (items?.Any() == true) or if (items?.Any() ?? false) or something similar.
I notice that items.Count == 0 is an error but items == null returns Ok in your first example.
That is odd.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With