Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Swapping objects without a placeholder

Tags:

c#

I was told that using a temp object was not the most effective way to swap elements in an array.

Such as:

Object[] objects = new Object[10];
// -- Assign the 10 objects some values
var Temp = objects[2];
objects[2] = objects[4];
objects[4] = Temp;

Is it really possible to swap the elements of the array without using another object?

I know that with math units you can but I cannot figure out how this would be done with any other object type.

like image 968
user762305 Avatar asked Dec 27 '22 20:12

user762305


1 Answers

Swapping objects with a temporary is the most correct way of doing it. That should rank way higher up in your priorities than speed. It's pretty easy to write fast software that ouputs garbage.

When dealing with objects, you just cannot do it differently. And this is not at all inefficient. An extra reference variable that points to an already existing object is hardly going to be a problem.

But even with numerical values, most clever techniques fail to produce correct results at some point.

like image 147
R. Martinho Fernandes Avatar answered Jan 08 '23 02:01

R. Martinho Fernandes