AUTOMATICALLY COPY ONE TO ARRAY TO ANOTHER ARRAY

Brad Pitt

Total Post:61

Points:429
Posted by  Brad Pitt
C# 
C#
 917  View(s)
Ratings:
Rate this:

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?

  1. Garry Winogrand

    Post:24

    Points:168
    Re: Automatically Copy one to array to another array

    array2 = array1;

    You now have two variables that refer to the same array

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!