Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 946
B. Clay Shannon-B. Crow Raven Avatar asked Dec 18 '15 18:12

B. Clay Shannon-B. Crow Raven


1 Answers

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.

like image 97
Hamid Pourjam Avatar answered Oct 09 '22 21:10

Hamid Pourjam