0

I wrote this code that fills an array and a second array copies the first. I change some numbers in the second array, but when I output both arrays, the first one has also changed. This is my code:

        int[] array1 = new int[5];
        int[] array2 = new int[5];
        int temp;

        for (int i = 0; i < array1.Length; i++)
        {
            array1[i] = i;
        }

        array2 = array1;
        temp = array2[2];
        array2[2] = array2[4];
        array2[4] = temp;

        for (int i = 0; i < array1.Length; i++)
        {
            richTextBox1.Text += array1[i].ToString() + " ";
        }
        for (int i = 0; i < array2.Length; i++)
        {
            richTextBox1.Text += array2[i].ToString() + " ";
        }

Can someone explain to me why the output is 0 1 4 3 2 0 1 4 3 2 instead of 0 1 2 3 4 0 1 4 3 2?

5 Answers 5

4

Because arrays are reference types, assigning array2 = array1 causes the array2 variable to reference the same array as array1.

Before assignment:

array1  --->  [0, 1, 2, 3, 4]

array2  --->  [0, 0, 0, 0, 0]

After assignment:

array1  --->  [0, 1, 2, 3, 4]
         /
array2  -     [0, 0, 0, 0, 0] <-- no longer reachable and will be garbage collected

To actually create a copy of an array, call Clone.

array2 = (int[])array1.Clone();

After assignment with Clone:

array1  --->  [0, 1, 2, 3, 4]

array2  -     [0, 0, 0, 0, 0] <-- no longer reachable and will be garbage collected
         \
          ->  [0, 1, 2, 3, 4]

Notice that the [0, 0, 0, 0, 0] array is never actually used, so you don't even need to allocate it.

//int[] array2 = new int[5];  <-- delete this line
int[] array2 = (int[])array1.Clone();
Sign up to request clarification or add additional context in comments.

Comments

3
array2 = array1;

You now have two variables that refer to the same array.

Comments

3
array2 = array1;

You are not copying the array - Array is a reference type and you are assigning another variable to point to the same array - there is only one array instance, so if you change its contents through one variable these changes are perceived through the other.

Comments

2

Because Arrays are reference type as others said.

You can use this instead:

Array.Copy(array1, array2, array2.Length);

Comments

2
array2 = array1;   // here you are losing reference to array2

Comments

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.