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
Given two variables, x, and y, swap two variables without using a third variable. The idea is to get a sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum.
Swap Numbers Using Temporary Variable In the above program, the temp variable is assigned the value of the first variable. Then, the value of the first variable is assigned to the second variable. Finally, the temp (which holds the initial value of first ) is assigned to second . This completes the swapping process.
Without a temporary variable (Tuple swap) Another way to swap the values of two variables, without using a temporary variable, is to use tuple packing and sequence unpacking. Tuples can be constructed in a number of ways, one of which is by separating tuple items using commas.
C# 7 introduced tuples which enables swapping two variables without a temporary one:
int a = 10; int b = 2; (a, b) = (b, a);
This assigns b
to a
and a
to b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With