What is the cause of the "Using an unrecognized local variable" error?

With this code:

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

I was getting a compiler error: "Using an unrecognized local variable" dataToAdd "

So I had to explicitly set "false" for bool:

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

In the context:

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

Why is this necessary? Do bools not have a default value of false?

+6
source share
1 answer

Because local variables are not initialized by default. You must initialize them explicitly. This is a compiler function to avoid future errors. This is specified in the language specification here and here .

The reason this is illegal in C # is because using an unassigned local is likely to be a mistake

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

+11
source

All Articles