7

After a day of troubleshooting I've managed to condense the problem to this tiny piece of code. Could someone explain to me why this doesn't work? I expect [markets] to be 0 2 4 6, [city] [county] and [streets] to be 0 1 2 3 when the messagebox is shown.

        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 = new string[4];
            foreach (string item in items)
            {
                for (int i = 0; i <= 3; i++)
                {
                    if (item == "apple")
                        value[i] = (2 * i).ToString();
                    else
                        value[i] = i.ToString();
                }

                if (item == "apple")
                    markets = value;
                else if (item == "banana")
                    streets = value;
                else if (item == "pineapple")
                    county = value;
                else
                    city = value;
            }
            MessageBox.Show("test");
        }

I'm looping through items in a foreach loop. If the item is "apple", then I expect [value] to be 0 2 4 6. Initially [markets] is assigned 0 2 4 6. However, if I execute the code step by step, it appears that the second time that the foreachloop is executed, [markets] is being overwritten. Why is that? What am I doing wrong here? [markets] should not be assigned a value a second time once banana has hit right?

3
  • 6
    You only have one array called value throughout this, that you keep overwriting and gradually assigning references from other variables to this same array. Commented Mar 31, 2020 at 13:56
  • 3
    Upvote for posting a minimal reproducible example Commented Mar 31, 2020 at 13:58
  • 1
    "However, if I execute the code step by step, it appears that the second time that the foreachloop is executed, [markets] is being overwritten. " This is because markets = value sets both references to the same array - and since you're assigning different values to the values array, naturally you can see these changes reflect regardless of what reference you're using to the array. Commented Mar 31, 2020 at 14:00

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand now that we're creating a link between two arrays instead of copying the values inside the array from one array to the other. I do find that a little strange though, but I understand that there might be a memory benefit involved.
@Maarten - it's not a link between two arrays. You need to get clear the difference between the variable, say markets, and the array that that variable currently references. All we're doing in the assignments is changing which array a particular variable is referencing.
0

Your main problem is that in the

            if (item == "apple")
                markets = value;
            else if (item == "banana")
                streets = value;
            else if (item == "pineapple")
                county = value;
            else
                city = value;

statements you do not create a new array - you just assign the reference to the object. And then you change your array in the for() cycle.

1 Comment

The solution is to create deep copies of the array or to copy the values. The main question was "What am i doing wrong here", not looking for the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.