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