Swapping variables in C#
In the project I am currently working on I often need to swap two non-integer variables around. It's not a difficult thing to do with a temp variable, but the frequency in which the current project uses it violates the DRY principle somewhat, so I decided to refactor it into a method.
What makes it interesting is the possible use of generics and a syntactic nicety I was not previously aware of. Without generics you would have to either create an overload for every single variable type you are going to swap, obviously time consuming, or convert it to the base object type and back again, negating the cleanliness of the code we are after.
private static void Swap<T>(ref T item1, ref T item2)
{
T temp = item1;
item1 = item2;
item2 = temp;
}
The use of generics avoids any need for boxing and unboxing (and excess code to do this) but still allows us to call the method with any type. We can call it like so:
string first = "a";
string second = "b";Swap<string>(ref first, ref second);
Console.WriteLine(first);
Console.WriteLine(second);
What's interesting, however, is that the compiler appears to be able to infer the type from the arguments, allowing it to be simplified to:
Swap(ref first, ref second);
This code, imho, is about as clean as you will get it with a clear intent and little boiler-plate code (excess code needed purely to help it out).
What amazes me most though is the fact it works with arrays.
int[] list = new int[2];
list[0] = 0;
list[1] = 1;Swap(ref list[0], ref list[1]);
Console.WriteLine(list[0]);
Console.WriteLine(list[1]);
The above works perfectly fine, though unfortunately, due to the way they work, lists do not.
There are a few times when I think this use of generics could alleviate a lot of boiler-plate code and boxing/unboxing where the base object is used.
