Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using null-conditional bool? in if statement [duplicate]

Why this code works:

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

but this code doesn't:

if (list?.Any())

saying Error CS0266 Cannot implicitly convert type 'bool?' to 'bool'

So why is it not a language feature making such an implicit conversion in the if statement?

like image 751
Centro Avatar asked Aug 09 '17 17:08

Centro


1 Answers

An if statement will evaluate a Boolean expression.

bool someBoolean = true;

if (someBoolean)
{
    // Do stuff.
}

Because if statements evaluate Boolean expressions, what you are attempting to do is an implicit conversion from Nullable<bool>. to bool.

bool someBoolean;
IEnumerable<int> someList = null;

// Cannot implicity convert type 'bool?' to 'bool'.
someBoolean = someList?.Any();

Nullable<T> does provide a GetValueOrDefault method that could be used to avoid the true or false comparison. But I would argue that your original code is cleaner.

if ((list?.Any()).GetValueOrDefault())

An alternative that could appeal to you is creating your own extension method.

public static bool AnyOrDefault<T>(this IEnumerable<T> source, bool defaultValue)
{
    if (source == null)
        return defaultValue;

    return source.Any();
}

Usage

if (list.AnyOrDefault(false))
like image 189
Derrick Moeller Avatar answered Nov 02 '22 14:11

Derrick Moeller