biggetje
biggetje

Reputation: 23

Altering array while keeping a backup copy

I have an array with 3 integers. I want to duplicate the array and change the first integer. For some magical reason, BOTH arrays get their first integer adjusted. I have no idea why this is happening and it's driving me crazy.

int [] numbers1 = {1, 2, 3}
int [] numbers2 = {3, 4, 5}

numbers2 = numbers1;

At this point I did a System.Console.Writeline to see both arrays are now {1, 2, 3}. So far so good.

numbers1[0] = 4;

When I'm doing a System.Console.Writeline I see BOTH arrays now look like {4, 2, 3}. I want numbers2 to stay the same.

Upvotes: 0

Views: 217

Answers (5)

deathismyfriend
deathismyfriend

Reputation: 2192

Currently you are only passing a reference. The numbers in the array are stored in memory. When you reference an object in memory it points to that object. It does not create a new object in memory when referencing, so you need to clone the ints into another array so that it points to a different object in memory.

         numbers2 = numbers1; 

You need to clone the arrays.

        numbers2 = (int[])numbers1.Clone();

As others have noted you can also use the .ToArray() method. This creates a copy of the items in the array.

       numbers2 = numbers1.ToArray();

Upvotes: 2

alireza amini
alireza amini

Reputation: 1742

try to use the .ToArray(); or Clone its work for me

my suggestion is .ToArray();

Upvotes: 0

TheKingPinMirza
TheKingPinMirza

Reputation: 8912

Did you try .ToArray() method? It will create new array not assign by reference Array2= Array.ToArray(); Click here for more about .ToArrray()

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117029

Arrays are a reference-type, regardless if the values of an array are value-types.

When you allocate an array you are creating a block of memory that the array variable points to. When you assign one array variable to another you are assigning the memory reference, not the values in the array. So both of your numbers1 and numbers2 arrays are pointing to the same set of values.

Now this should make sense. Imagine if you have an array with a million elements then every time you assigned or passed the array around you made a copy it would be an horrific performance issue.

So, you need to explicitly say when you want to copy an array.

The easiest way is to do this:

numbers2 = numbers1.ToArray(); // yes, this copies the entire array.

Upvotes: 1

NeverHopeless
NeverHopeless

Reputation: 11233

Using this:

numbers2 = numbers1;

You are assigning the reference of first array to the second array. So it loses your original contents and start pointing to numbers1. If you want to copy few or all items of numbers1 to numbers2 then either use Clone() or use loop to copy elements.

Upvotes: 0

Related Questions