- Home /
 
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 :D
If not, an answer here would be appreciated as well. Thanks in advance.
I just run this
 List<int> list = new List<int>();
 list.Add(0);
 list.Add(1);
 list.Add(2);
         
 int temp = list[1];
 list[1] = list[2];
 list[2] = temp;
 for (int i = 0; i < list.Count; i++) // Loop with for.
 {
     Console.WriteLine(list[]);
 }
 
                  And the output was 0 2 1. Could you be printing the list value before 3rd one is assigned to temp. 
Answer by DoTA_KAMIKADzE · Apr 08, 2015 at 06:01 PM
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:

And that^ is an expected behavior.
Actually you're correct, I was storing it in another variable as such:
 if(list[parent] >= insert){
     int temp = list[parent];
     list[parent] = insert;
     insert = temp;
     index = parent;
 }else{
     ...
 
                  Ins$$anonymous$$d of actually changing the values of the list items. Don't know why I overlooked that.
Your answer