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

守給你的承諾、 提交于 2021-01-22 03:40:06

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/45596941/using-null-conditional-bool-in-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!