Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a generic swap method in the framework?

Tags:

.net

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?

like image 916
Bob Avatar asked May 28 '09 18:05

Bob


People also ask

What are generic methods in C#?

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.

What is type parameter in C#?

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.


1 Answers

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.

like image 147
Reed Copsey Avatar answered Sep 16 '22 23:09

Reed Copsey