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
we can do that by doing a simple trick
BenAlabaster showed a practical way of doing a variable switch, but the try-catch clause is not needed. This code is enough.
The usage is the same as he shown:
You could also use an extension method:
Use it like this:
Both ways uses a temporary variable in the method, but you don't need the temporary variable where you do the swapping.
C# 7 introduced tuples which enables swapping two variables without a temporary one:
This assigns
b
toa
anda
tob
.Very simple code for swapping two variables: