There's some good, and some bad, about your expectations for your code.
Let's go through what your code is actually doing:
int[] newPermutation = new int[m_permutation.Length];
This will declare a new variable, newPermutation
, to be an array of ints, and then construct a new int array containing m_permutation.Length
elements.
So far so good.
The next line, not so much:
newPermutation = m_permutation;
This line will actually replace the reference in your array variable newPermutation
to, after the assignment, refer to the same array as m_permutation
.
Let's consider what an array variable actually is.
When you do this:
int[] x = new int[5];
Then you're doing a couple of things:
- You're declaring a variable,
x
- You're constructing a new object containing the int array
- You're assigning the variable,
x
to refer to this object
After the 2nd line:
newPermutation = m_permutation;
you're essentially saying this:
- OK, you know that array we just constructed? Forget that
- Let's now refer to this other array, the one that the variable
m_permutation
is also referring to.
So when this line executes:
newPermutation[0] = 5;
You're essentially saying: The array that newPermutation
is now referring to, its first element should now have the value 5.
Since newPermutation
at this point refers to the same array as m_permutation
, it appears that you're modifying an additional array but in reality you only have one array. You do, however, have two variables referring to the same array.
I recommend you read my answer here regarding pointers since this is relevant.
However, there is an easy fix to your problem.
You can ask for a copy of the array, instead of a reference to the original one.
Simply change your code to this:
int[] newPermutation = m_permutation.ToArray();
The .ToArray()
method is guaranteed to return a new array, so this won't be shared with the original.
Bear in mind, however, that if you do this with anything more complex than an int, such as an object, you're only getting copies of the object references, not the objects themselves. You can get back to Stack Overflow with new questions when/if you get to this point.