-1

I have a jagged array that I pass to object constructor but whenever I edit the array that I passed as parameter, the array inside the instance of the object also gets edited for some reason.

bool[][] clickedArray = new bool[7][];
clickedArray[0] = new bool[3];
clickedArray[1] = new bool[3];
clickedArray[2] = new bool[3];
clickedArray[3] = new bool[2];
clickedArray[4] = new bool[3];
clickedArray[5] = new bool[3];
clickedArray[6] = new bool[4];

I read some ints from a file and set the bools to true or false depending on the ints. By default, all elements of the jagged array are set to false:

for (int i = 0; i < clickedArray.Length; i++) // i < 7
        {
            for (int j = 0; j < clickedArray[i].Length; j++) 
            {
                clickedArray[i][j] = false;
            }
        }

I also have a List of objects. I call the constructor by adding new instance of the object to the list: buildsList.Add(new Builds(tokens[0], clickedArray));

Here is the constructor:

public Builds(string buildName, bool[][] jagged)
    {
        this.buildName = buildName;
        jaggedArray = jagged;
    }

I don't know why but when I, for example, reset the array and then call a function such as:

int selection = comboBox1.SelectedIndex;
clickedArray = buildsList[selection].getJaggedArray();

it turns out that the jagged array from the object inside the list also had it's values reset.

Domcho
  • 1
  • 2

1 Answers1

0

Arrays in .NET are object on the heap, so you have a reference. That reference is passed by value, meaning that changes to the contents of the array are reflected anywhere.

So: jaggedArray = jagged;

they have the same reference pointer to the same address in the memory.

Use Array.Copy method to avoid that issue in order to copy elements fr om the source array to the destination. Check how to use Array.Copy Method.

Hussein Salman
  • 7,806
  • 15
  • 60
  • 98
  • Array.Copy(jagged, jaggedArray, 7); inside the constructor does not fix the problem. Am I doing it wrong? – Domcho Oct 13 '17 at 04:18