0

I have tried

int[] secondArray = firstArray;

but whenever I alter the first array it changes in the second, is there a function that allows me to alter the first without it affecting the second?

Thanks.

Sup
  • 307
  • 3
  • 5
  • 13
  • 1
    You need to read up on references in .NET. The code above creates a second instance of the array, but they point to the same location in memory and therefore the same object. There's a very good article by Jon Skeet here - [References and Values](http://jonskeet.uk/csharp/references.html) – Tim Apr 01 '15 at 23:59
  • You could loop and add the values of your first array into your second array. Also, see http://stackoverflow.com/questions/733243/how-to-copy-part-of-an-array-to-another-array-in-c to learn about the Array.Copy method, which is probably easier. – disappointed in SO leadership Apr 02 '15 at 00:01

2 Answers2

2

That's because you have an object that is an "array of integer" which firstArray references. Your assignment statement just increments the reference count of the object

I think what you may be looking for is a way to provide a shallow copy of the firstArray? If so, use the clone method

jhenderson2099
  • 956
  • 8
  • 17
2

Like Tim said, you need to understand why this happens, so read up on it. :)

But you could use the Array.CopyTo method:

int[] firstArray = new int[20];
int[] secondArray = new int[20];
firstArray.CopyTo(secondArray, 0);

But you will have to make sure that you wont overflow the second array yourself, because otherwise, it will throw an exception.

Malte R
  • 468
  • 5
  • 16