Search code examples
c#linqnull-conditional-operator

C# 6.0 null-conditional operator in if statements


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?


Solution

  • 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