Well, the code you posted ( ref cards[n] ) can only work with an array (and not with a list) - but you would just use (where foo and bar are two values):
static void Swap(ref int foo, ref int bar) { int tmp = foo; foo = bar; bar = tmp; }
Or perhaps (if you want atomic):
Interlocked.Exchange(ref foo, ref bar);
Personally, I donβt think I would bother with the swap method, but just do it directly; this means that you can use (either for a list or for an array):
int tmp = cards[n]; cards[n] = cards[i]; cards[i] = tmp;
If you really wanted to write a swap method that worked in an array of list or , you would need to do something like:
static void Swap(IList<int> list, int indexA, int indexB) { int tmp = list[indexA]; list[indexA] = list[indexB]; list[indexB] = tmp; }
(it would be trivial to do this general), however, the original version of "inline" (ie not the method) working on the array will be faster.
Marc Gravell Feb 16 '09 at 9:34 2009-02-16 09:34
source share