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
If you want to swap 2 string variables:
An helper method accordingly:
Usage would be then:
For the sake of future learners, and humanity, I submit this correction to the currently selected answer.
If you want to avoid using temp variables, there are only two sensible options that take first performance and then readability into consideration.
Swap
method. (Absolute best performance, next to inline temp variable)Interlocked.Exchange
. (5.9 times slower on my machine, but this is your only option if multiple threads will be swapping these variables simultaneously.)Things you should never do:
Decimal
is not a CPU primitive and results in far more code than you realize.Because everyone loves hard numbers, here's a program that compares your options. Run it in release mode from outside Visual Studio so that
Swap
is inlined. Results on my machine (Windows 7 64-bit i5-3470):Code:
With tuples
Here is some different process to swap two variables
Works for all types including strings and floats.
This works great.