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?
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With