How can I keep a variable after the update?

advertisements

I have a method for swapping 2 Items in a list. The problem is that the 'temp' variable updates after I change the value of itemA. How do I prevent 'temp' from updating after I initialize it?

void SwapItems(Item itemA, Item itemB)
{
    Item temp = itemA;

    itemA.OriginItemPosition = itemB.OriginItemPosition;
    itemA.OriginItemRectangle = itemB.OriginItemRectangle;

    itemB.OriginItemPosition = temp.OriginItemPosition;
    itemB.OriginItemRectangle = temp.OriginItemRectangle;
}


That is because temp1 holds the reference of itemA, and not it's values copied. To swap items in your case I would do:

void SwapItems(Item itemA, Item itemB)
{
    var temp1 = itemA.OriginItemPosition;
    var temp2 = itemA.OriginItemRectangle;

    itemA.OriginItemPosition = itemB.OriginItemPosition;
    itemA.OriginItemRectangle = itemB.OriginItemRectangle;

    itemB.OriginItemPosition = temp1;
    itemB.OriginItemRectangle = temp2;
}

You could also have something like this, which some may find nicer:

// Swaps the references themselves for reference-types.
void Swap<T>(ref T a, ref T b)
{
    var tmp = a;
    a = b;
    b = tmp;
}

// Swaps the properties between two Item objects.
void SwapItems(Item a, Item b)
{
    Swap(ref a.OriginalItemPosition, ref b.OriginalItemPosition);
    Swap(ref a.OriginalItemRectangle, ref b.OriginalItemRectangle);
}