Swapping Items in List Replaces Value Instead

Hey all. I’m trying to swap two items in a list and the values just start replacing each other versus actually switching. For example:

List<int> list = new List<int>();

list.Add(1);
list.Add(7);
list.Add(8);
list.Add(15);

int temp = list[2];
list[2] = list[3];
list[3] = temp;

Theoretically the list should print [1, 7, 15, 8] but instead it prints [1, 7, 15, 15]. I assume its because temp is referencing list[2] so when list[2] becomes 15, so does temp. Anyone know why that is, or how to step around it?

I’ve looked around pretty earnestly for a solution to this on the web and couldn’t find one, which is surprising since this seems like a pretty basic problem. If there is an answer somewhere, a redirect would work just fine :smiley:

If not, an answer here would be appreciated as well. Thanks in advance.

You’re doing something else with your list apart of the code above.

I’ve even run it in a single run just to show you the result:

List<int> list = new List<int>();
list.Add(1);
list.Add(7);
list.Add(8);
list.Add(15);
int temp = list[2];
list[2] = list[3];
list[3] = temp;
foreach (int ila in list) Debug.Log(ila);

Result:

alt text

And that^ is an expected behavior.