Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with editing list<double[]> in c#

Tags:

c#

list

I am passing a list of type double[] to a function in a class, editing the values within a function using a tempList, then returning the edited values. But the originalList being passed is being edited as well which I do not want them edited to match the tempList.

Here is the code.

List<double[]> newList = new List<double[]();
newList = myClass.myFunction(value, originalList);

// myClass
...

// myFunction
public List<double[]> myFunction(int value, List<double[]> myList)
{
    List<double[]> tempList = new List<double[]>();
    for (int i = 0; i < myList).Count; i++)
    {
       tempList.Add(myList[i]);
    }


    // Do stuff to edit tempList

    return tempList;
}
like image 522
Questioner Avatar asked May 24 '12 14:05

Questioner


1 Answers

Bear in mind that arrays are reference types. When you add an array to tempList, only a reference to the array is being added, so that myList and tempList both refer to the same double[] objects.

Instead, you need to make a clone of the arrays:

for (int i = 0; i < myList.Count; i++)
{
   tempList.Add((double[])myList[i].Clone());
}
like image 192
thecoop Avatar answered Sep 18 '22 12:09

thecoop