I used this code to copy one 2D array to another 2D array:
Array.Copy(teamPerformance, 0,tempPerformance,0, teamPerformance.Length);
However, when I change some data in tempPerformance
then these changes also apply to teamPerformance
.
What should I do to control that?
Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.
You need Clone()
double[,] arr = { {1, 2}, {3, 4} }; double[,] copy = arr.Clone() as double[,]; copy[0, 0] = 2; //it really copies the values, not a shallow copy, //after: //arr[0,0] will be 1 //copy[0,0] will be 2
This is correct: Array.Copy
performs a shallow copy, so the instances of arrays inside the inner dimension get copied by reference. You can use LINQ to make a copy, like this:
var copy2d = orig2d.Select(a => a.ToArray()).ToArray();
Here is a demo on ideone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With