Szczepan
Szczepan

Reputation: 365

Swap two object when they are on two different list

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

enter image description here

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:

enter image description here

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.

enter image description here

It could be easly done in C++. Is it posible in C#?

Upvotes: 1

Views: 376

Answers (3)

tia
tia

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

Pankaj Gupta
Pankaj Gupta

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

Boris Sclauzero
Boris Sclauzero

Reputation: 111

I suppose you need also to change the reference in RedList1 and RedList2

RedList1[0] = Element3;
RedList2[0] = ELement1;

Upvotes: 0

Related Questions