C# changing previously assigned values

80 Views Asked by At

I have a function that gets called on a two dimensional array "a" and alters the array. However, it also alters any array that was previously assigned to "a", before even calling the function. I'm not sure if I understand why!

char[][] copy;

copy = a; // a is a also a two dimensional char array

DFSfunction(a); //DFSfunction alters values of a

So after DFSfunction is called, values of "copy" is also altered. How can I keep a copy of the original "a"?

Thank you!

1

There are 1 best solutions below

4
On

Arrays are mutable in C# so if you change a in your example it will have an effect on copy as well, since they still have the same reference

So when you wrote

copy = a

copy is just pointing to the same a array.

To solve this you can use Array.Copy..

In your example it can look something like this :

char[][] copy;
char[][] a;

Array.Copy(a, copy, a.Length);

You can also use Array.Clone :

var copy = (char[][])a.Clone();