I'd like to be able to swap two variables without the use of a temporary variable in C#. Can this be done?
decimal startAngle = Convert.ToDecimal(159.9);
decimal stopAngle = Convert.ToDecimal(355.87);
// Swap each:
// startAngle becomes: 355.87
// stopAngle becomes: 159.9
The right way to swap two variables is:
In other words, use a temporary variable.
There you have it. No clever tricks, no maintainers of your code cursing you for decades to come, no entries to The Daily WTF, and no spending too much time trying to figure out why you needed it in one operation anyway since, at the lowest level, even the most complicated language feature is a series of simple operations.
Just a very simple, readable, easy to understand,
t = a; a = b; b = t;
solution.In my opinion, developers who try to use tricks to, for example, "swap variables without using a temp" or "Duff's device" are just trying to show how clever they are (and failing miserably).
I liken them to those who read highbrow books solely for the purpose of seeming more interesting at parties (as opposed to expanding your horizons).
Solutions where you add and subtract, or the XOR-based ones, are less readable and most likely slower than a simple "temp variable" solution (arithmetic/boolean-ops instead of plain moves at an assembly level).
Do yourself, and others, a service by writing good quality readable code.
That's my rant. Thanks for listening :-)
As an aside, I'm quite aware this doesn't answer your specific question (and I'll apologise for that) but there's plenty of precedent on SO where people have asked how to do something and the correct answer is "Don't do it".
Yes, use this code:
The problem is harder for arbitrary values. :-)
In C# 7:
A binary XOR swap with a detailed example:
XOR truth table:
Input:
Step 1: a = a ^ b
Step 2: b = a ^ b
Step 3: a = a ^ b
Output:
For binary types you can use this funky trick:
As long as a and b are not the exact same variable (e.g. aliases for the same memory) it works.
If you can change from using
decimal
todouble
you can use theInterlocked
class. Presumably this will be a good way of swapping variables performance wise. Also slightly more readable than XOR.Msdn: Interlocked.Exchange Method (Double, Double)