How to null coalesce for Boolean condition?

Viewed 8454

I'm trying to safely check if an IList<> is not empty.

var Foo = Bar.GimmeIListT(); // Returns an IList<SomeObject>
if (Foo?.Any())
    // Do cool stuff with items in Foo

But there is an error with the condition:

Cannot implicitly convert 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)

So it seems the condition evaluates to a nullable bool, so I try

if (Foo?.Any().Value())

But this is no good either:

'bool' does not contain a definition for 'Value' and no extension .... blah blah blah

So in the first instance it complains that it is a nullable bool but in the second it complains that it isn't.

As another avenue I try:

if (Foo?.Any() == true)

This works - but it shouldn't because this uses an implicit conversion which the first message said it didn't want!

What is going on? What is the correct way to do this?

4 Answers

more syntactic sugar, the null-coalescing operator. C# 8.0 or later

if (Foo?.Any() ?? false) { }
Related