tags:

views:

73

answers:

2

Does a method like this exist anywhere in the framework?

public static void Swap<T>(ref T left, ref T right) {
    T temp;
    temp = left;
    left = right;
    right = temp;
}

If not, any reason why?

+4  A: 

There is Interlocked.Exchange. This does it in a thread-safe, atomic call.


Edit after comments:

Just to clarify how this works using Interlocked.Exchange, you would do:

left = Interlocked.Exchange(ref right, left);

This will be the equivalent (in effect) to doing:

Swap(ref left, ref right);

However, Interlocked.Exchange does this as an atomic operation, so it's threadsafe.

Reed Copsey
Interlocked.Exchange sets a value, it doesn't actually swap values. You would still need to save a temp, and call Interlocked.Exchange twice, so you don't really gain anything.
jrista
Interlocked.Exchange is not really equivalent of the specified Swap. It only changes the first value and doesn't touch the second (itself).
Mehrdad Afshari
@Mehdrad: left = InterlockedExchange(ref right, left);
Reed Copsey
@jrista: Why would you need to call it twice? Interlocked.Exchange returns the ~original~ value, so you only need to call it once, and use the returned value. See my edit.
Reed Copsey
Nice find! ----
iik
@Reed: That's why I mentioned "itself," in my comment. As mentioned in the answer, it's also different due to atomic semantics that might have overhead...
Mehrdad Afshari
+2  A: 

No, the framework does not have such a method. Probably the reason is there's not much benefit to have it built-in and you could very easily (as you did) add it yourself. This also requires use of ref as parameter, which will greatly limit the use cases. For instance, you couldn't do this:

List<int> test; 
// ...
Swap(ref test[0], ref test[1]); // won't work, it's an indexer, not an array
Mehrdad Afshari