This will not work. You can simply skip the explanation and see the code below :)
How do you know the operator ?. returns null if the child is null. But what happens if we try to get a member that does not contain NULL, like the Any() method that returns bool ? The answer is that the compiler will "wrap" the return value in Nullable<> . For example, Object?.Any() will give us bool? (which is Nullable<bool> ), not bool .
The only thing that does not allow us to use this expression in an if is that it cannot be implicitly executed in bool . But you can do the comparison explicitly, I prefer to compare with true as follows:
if (c?.Object?.Any() == true) Console.Write("Container has items!");
Thanks to @DaveSexton there is another way:
if (c?.Object?.Any() ?? false) Console.Write("Container has items!");
But for me, comparison with true seems more natural :)
Eldar Dordzhiev Sep 04 '14 at 13:54 on 2014-09-04 13:54
source share