2

I want to save my current state of array and later change that array but when I save my array in list and then change my array, array in list also changes. This is a sample code and a part of my code :

void main()
{
    List<int[]> lisarr = new List<int[]>();
    int[] a = new int[1];
    a[0] = 1;
    lisarr.Add(a);
    a[0] = 10;
    // at this time lisarr[0] also changes
   ....
}

If you trace this code notice that my array in list also change, but I don't want this. How can I fix this problem?

1 Answer 1

6

Add a copy of your array:

List<int[]> lisarr = new List<int[]>();
int[] a = new int[1];
a[0] = 1;
lisarr.Add(a.ToArray());
a[0] = 10;
1
  • 2
    Just for clarification, this works because ToArray() internally copies all of its elements to a new array using Array.CopyTo() and then returns it.
    – Cᴏʀʏ
    Mar 7, 2013 at 15:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.