2

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

6 Answers 6

2

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();
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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

Comments

0

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);

Comments

0

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

Comments

0

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];

1 Comment

Thank everyone for very helpful comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.