Sreedhar Sreedhar - 10 months ago 63
C# Question

Swap two variables without using a temporary variable

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


First of all, swapping without a temp variable in a language as C# a very bad idea.

But for the sake of answer, you can use this code:

startAngle = startAngle+stopAngle;
stopAngle = startAngle-stopAngle;
startAngle = startAngle-stopAngle;

Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating points.

If you want to hide the temp variable, you can use a utility method:

public static class Foo {

    public static void Swap<T> (ref T lhs, ref T rhs) {
        T temp = lhs;
        lhs = rhs;
        rhs = temp;