user2079550 user2079550 - 3 months ago 30
C# Question

Copy one 2D array to another 2D array

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?

Answer

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.