Reputation: 365
In my example I got 8 Objects.
Assume that first element of BlueList is refered to Element1 and first element of RedList1 is also refered to Element1
Now I want to swap Object1 with Object3, but when I make something like this:
Pseudo Code:
Object Temp = BlueList1[0];
BlueList1[0] = BlueList[1];
BlueList1[1] = Temp;
The result is:
Because I only switched list refferences. How to safety swap two addresses of object, like in picture below? As You can see Element1 is switched with Element3.
It could be easly done in C++. Is it posible in C#?
Upvotes: 1
Views: 376
Reputation: 9698
I think you need to make a wrapper class.
class Element<T> {
public T Object { get; set; }
public void SwapWith(Element<T> other) {
// warning: this is not thread-safe
T tmp = other.Object;
other.Object = this.Object;
this.Object = tmp;
}
}
Then you can make change like
BlueList1[0].SwapWith(BlueList[1]);
Upvotes: 2
Reputation: 388
because you changing the value not reference because list is reference type so you need to change the reference so create one method like that do looping and call that method and pass your values.
void swap(int ref a , int ref b)
{
int temp =a;
a=b;
b =temp;
}
Hope it will be helpful for you Thanks
Upvotes: -1
Reputation: 111
I suppose you need also to change the reference in RedList1 and RedList2
RedList1[0] = Element3;
RedList2[0] = ELement1;
Upvotes: 0