C# Null propagating operator / Conditional access expression & if blocks

It won’t work this way. You can just skip the explanation and see the code below 🙂

As you know ?. operator will return null if a child member is null. But what happens if we try to get a non-nullable member, like the Any() method, that returns bool? The answer is that the compiler will “wrap” a return value in Nullable<>. For example, Object?.Any() will give us bool? (which is Nullable<bool>), not bool.

The only thing that doesn’t let us use this expression in the if statement is that it can’t be implicitly casted to bool. But you can do comparison explicitly, I prefer comparing to true like this:

if (c?.Object?.Any() == true)
    Console.Write("Container has items!");

Thanks to @DaveSexton there’s another way:

if (c?.Object?.Any() ?? false)
    Console.Write("Container has items!");

But as for me, comparison to true seems more natural 🙂

Leave a Comment