Sup
Sup

Reputation: 307

Duplicating an array so it becomes unaffected c#

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.

Upvotes: 0

Views: 69

Answers (2)

Malte R
Malte R

Reputation: 488

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.

Upvotes: 2

jhenderson2099
jhenderson2099

Reputation: 964

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

Upvotes: 2

Related Questions