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?
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?
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.
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