C# strange behaviour in foreach loop
You gradually end up with all of your various variables referencing the same array (value
), with whatever values are written into that array by the last iteration being set.
There's a very similar way of writing this code that avoids the issue:
private void pieceoftestcode()
{
string[] county = new string[4];
string[] city = new string[4];
string[] markets = new string[4];
string[] streets = new string[4];
string[] items = new string[4] { "apple", "banana", "pineapple", "juice" };
string[] value;
foreach (string item in items)
{
if (item == "apple")
value = markets;
else if (item == "banana")
value = streets;
else if (item == "pineapple")
value = county;
else
value = city;
for (int i = 0; i <= 3; i++)
{
if (item == "apple")
value[i] = (2 * i).ToString();
else
value[i] = i.ToString();
}
}
MessageBox.Show("test");
}
Now, each time through the loop value
get assigned a reference to a different array1 and so the for
loop doesn't overwrite its previous efforts.
1Assuming items
doesn't contain any duplicate items nor more than one non-apple, -banana or -pineapple item.