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?
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))