"Use of unassigned local variable" 错误的原因是什么?

What is the reason for "Use of unassigned local variable" error?

使用此代码:

bool dataToAdd;
if (null == _priceComplianceDetailList) return dataToAdd;

我遇到编译器错误,“使用未分配的局部变量 'dataToAdd'

所以我必须明确地将 "false" 分配给 bool:

bool dataToAdd = false;
if (null == _priceComplianceDetailList) return dataToAdd;

在上下文中:

private bool PopulateSheetWithDetailData()
{
    bool dataToAdd = false;
    if (null == _priceComplianceDetailList) return dataToAdd;
    List<PriceComplianceDetail> _sortedDetailList =
    . . .
    return _sortedDetailList.Count > 0;
}

为什么有必要?布尔值不是有默认值 false 吗?

因为默认情况下不初始化局部变量。您应该明确地初始化它们。这是一个编译器功能,可以避免将来出错。语言规范 here and here 对此进行了澄清。

The reason this is illegal in C# is because using an unassigned local has high likelihood of being a bug

如果您想知道做出此决定的原因,请参阅 here