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, thenitems?.Count
is null, too.and
null == 0
is a comparison that results in false. so theif
is happy.but
items?.Any()
will also be null - andif(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:
will do the trick