M. Mohebbi
M. Mohebbi

Reputation: 27

Why changing one array changes another array in C#?

I have a two dimensional array namely States in C#. I build a one dimensional array, namely SubState, from States. When I change SubState, States changes too. I want States be unchanged. Thanks

int[] SubState = State [0];
SubState[0]-=1; //State[0][0] is also changed here

Upvotes: 2

Views: 2046

Answers (6)

Rahul
Rahul

Reputation: 77936

int[] SubState = State [0]; is just another reference to the state array and so can be changed via it as well.

What you probably want to do, is create a separate array from the state array like

int[] substate = new int[state.GetLength(0)];
state.CopyTo(substate, 0);

Upvotes: 2

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37113

Obviously your element at position 0 of State is an array of int which is a reference-type. Thus both SubState and State reference the same array which is why changes to any of their elements are reflected by both. To overcome this problem you may create a copy of your State-array and copy its values to SubState:

States.CopyTo(SubStates, 0);

EDIT: Thius assumes that SubStates was already initialized with the same size as States. e.g:

int[] SubStates = new int[States[0].Length];

Upvotes: 0

Chino
Chino

Reputation: 821

That is because when you assign the array you pass its reference you are not making a copy of it. Look at the msdn link on the array copy method https://msdn.microsoft.com/en-us/library/System.Array.Copy(v=vs.110).aspx

Upvotes: 1

psoshmo
psoshmo

Reputation: 1570

instead of

int[] SubState = State [0];

try

int[] SubState = new int[State[0].Length];
Array.Copy(State[0],Substate, Substate.Length)

So you are not simply assigning a new reference, but are actually copying the array correctly

Upvotes: 0

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

In my mind your State definition is:

int[][] State;

Array is a reference type and when you copy an element from the State array you get a reference to the array from the first list and the both references map to the same int[] array. So when you change array stored at SubArray you use a link to the same array.

The simple fix is a copy of the source array

var SubState = State[0].ToArray();

Upvotes: 2

Tripp Kinetics
Tripp Kinetics

Reputation: 5459

You are not building a new one-dimensional array. You are simply creating a new reference to the first row of your two-dimensional array. If you actually want to build a new one-dimensional array, you have to iteratively copy the first row of your two-dimensional array.

Try:

int[] SubState = new int[States[0].length];
States[0].CopyTo(SubState, 0);

Upvotes: 0

Related Questions