Search code examples
c#.netbooleandefaultdefault-value

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


With this code:

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

I was getting a compiler error, "Use of unassigned local variable 'dataToAdd'"

So I had to explicitly assign "false" to the bool:

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

In context:

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

Why is it necessary? Don't bools have a default value of false?


Solution

  • Because local variables aren't initialized by default. You should initialized them explicitly. It is a compiler feature to avoid future mistakes. It is clarified in language specification here and here.

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

    If you want to know the reason for this decision see here.