7

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?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • 4
    The default only applies to class members, local variables in methods must be explicitly assigned. – Lee Dec 18 '15 at 18:08
  • 1
    Also you can remove completely the variable since you are returning based on the count of the list and in the first if block you can return false directly. – Mihail Stancescu Dec 18 '15 at 18:12

1 Answers1

13

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.

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • 1
    Also relevant is [section 5.1.7](https://msdn.microsoft.com/en-us/library/aa691170(v=vs.71).aspx). Specifically: "A local variable introduced by a _local-variable-declaration_ is not automatically initialized and thus has no default value." – Joe Farrell Dec 18 '15 at 18:17
  • Added to the answer, Thanks @JoeFarrell, – Hamid Pourjam Dec 18 '15 at 18:18