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
You can try the following code. It is much more better than the other code.
The simple way to swap 2 numbers in just one line:
eg: a=1, b=2
Step 1: a=(1+2) - (b=1)
Step 2: a=3-1
=> a=2 and b=1
Efficient way is to use:
C Programming:
(x ^= y), (y ^= x), (x ^= y);
Java:
x = x ^ y ^ (y = x);
Python:
x, y = y, x
Note: Most common mistake people make: //Swap using bitwise XOR (Wrong Solution in C/C++)
Source: GeeksforGeek
َ
First of all, swapping without a temporary variable in a language as C# is a very bad idea.
But for the sake of answer, you can use this code:
Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.
If you want to hide the temporary variable, you can use a utility method:
With C# 7, you can use tuple deconstruction to achieve the desired swap in one line, and it's clear what's going on.