c# val / ref - indirectly canging a value problem

Hi, below is a short snipet of the relevant methods:

in the first part i’m iterating through a an array of integers. for each integer i’m getting a different value, also an array of integers that i modify, when a certain condition is met.

Now the strange part is: the source value (_tiles[t].texState through _map.getTexState) shouldn’t be affected - only the copy (int[ ] a) - but somehow the source is being changed.

Output of the getter method below is:

a: “getTextState of 17=0000”
b: “getTextState of 17=1000”

How is that even possible? I assume i’m accidently messing up val/ref here somehow without knowing it.

for (x=0; x < l.Length; x++) {

				if (l[x] != -1) {
					int[] a = _map.getTexState(l[x]);

					for (y=0; y < a.Length; y++) {

						if (x==y)
							a[y] = 1;
					}
					int[] b = _map.getTexState(l[x]);


...

public int[] getTexState(int t) {

		int[] s = _tiles[t].texState;

		string d = "getTextState of " + t.ToString() + "=" + s[0].ToString() + s[1].ToString() + s[2].ToString() + s[3].ToString();
		Debug.Log(d);

		return s;
	}

An array itself, regardless of its element type, is a reference. Both int[ ] a and int[ ] b end up referencing the same _map._tiles[t].textState integer array, so when you assign a[y] = 1 you’re modifying the _map._tiles[t].textState array, which int[ ] b ends up referencing as well.

It looks like what you want to do on line 18 is:

var s = new int[_tiles[t].texState.Length];
_tiles[t].texState.CopyTo(s, 0);

Ok, didn’t know that - i thought the default was value and not reference. And yes your solution is what i was looking for. Big thank you!

Right on, good coding to you!