How to Swap Variable Values Without the Use of Temporary Variable in C#

Bilal Shahid Feb 02, 2024
  1. Use Tuple Assignment in C#
  2. Use the + Operator to Get Around the Temporary Variable Used in C#
  3. Use a Function to Swap Values Rather Than Explicit Implementation to Hide Temporary Variable Use in C#
  4. How to Use the XOR Operator to Swap in C#
How to Swap Variable Values Without the Use of Temporary Variable in C#

So, let’s say you are writing a code now and want to exchange variable values. You will probably do something like this:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    var val_swap = val_one;
    val_one = val_two;
    val_two = val_swap;

    Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);
  }
}

Now here, you first create a temporary variable called val_swap, then you copy the val_one value to it so that after the val_one value is modified, you can easily copy the original val_one value back into val_two by assigning the value from val_swap into it.

Today, we will be looking at eliminating the use of this temporary variable and performing such an exchange without any other allocations.

Use Tuple Assignment in C#

A very simple method that you can now utilize is to use a TUPLE assignment as follows.

(val_one, val_two) = (val_two, val_one);

Console.WriteLine("The value after swapping from the tuple method is: " + val_one + " and -> " +
                  val_two);

Complete Code:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    (val_one, val_two) = (val_two, val_one);

    Console.WriteLine("The value after swapping from the tuple method is: " + val_one + " and -> " +
                      val_two);
  }
}

Output:

The value after swapping from the tuple method is: 234 and -> 123

This method has also been used in Python; however, not subjected to tuples.

However, sometimes you have to use tricks to get what you want. Let’s look at an example below.

Use the + Operator to Get Around the Temporary Variable Used in C#

Let’s say we have two numbers; 7 and 9. The first variable has the value 7, and the second variable has the value 9.

If we add 9 to 7, we’ll get 16. Let’s assign 16 to the first variable now.

To put 9 as the value of the first variable, you have to deduct the value of 9 from the second variable, which would become 15-9 = 7; use this value and subtract it from 15 in the first variable to now get the value 9.

val_one += val_two;
val_two = val_one - val_two;
val_one = val_one - val_two;

Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);

Complete Code:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    val_one += val_two;
    val_two = val_one - val_two;
    val_one = val_one - val_two;

    Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);
  }
}

Output:

The value after swapping is: 234 and -> 123

You can notice how this uses simple arithmetic to stop using temporary variables while swapping. On the other hand, this may become ineffective if there are very large accurate values, and using such arithmetic may result in the loss of some values.

If you want to hide the implementation and not just remove the use of a temporary variable, you can use something such as the following.

Use a Function to Swap Values Rather Than Explicit Implementation to Hide Temporary Variable Use in C#

You can do something as follows.

static void swap(ref int x, ref int y) {
  var temp = x;
  x = y;
  y = temp;
}

And then call it below as:

swap(ref val_one, ref val_two);
Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);

Complete Code:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    swap(ref val_one, ref val_two);
    Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);
  }

  static void swap(ref int x, ref int y) {
    var temp = x;
    x = y;
    y = temp;
  }
}

Output:

The value after swapping is: 234 and -> 123

How to Use the XOR Operator to Swap in C#

Let’s look at the code below.

val_one ^= val_two ^= val_one ^= val_two;

Complete Code:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    val_one ^= val_two ^= val_one ^= val_two;
    Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);
  }
}

And its output:

The value after swapping is: 0 and -> 123

You’ll notice that the first value is 0 even though the second variable now has the value of the first variable and works properly.

So how do we fix this? Let’s first write a code as follows.

val_one ^= val_two;
val_two ^= val_one;
val_one ^= val_two;

Complete Code:

using System;

public class Program {
  public static void Main(string[] args) {
    var val_one = 123;
    var val_two = 234;

    val_one ^= val_two;
    val_two ^= val_one;
    val_one ^= val_two;
    Console.WriteLine("The value after swapping is: " + val_one + " and -> " + val_two);
  }
}

And now the output is:

The value after swapping is: 234 and -> 123

So what’s going on? Let’s first understand the code given in the first statement.

That can be expanded as follows.

val_one = val_one ^ val_two;
val_two = val_two ^ val_one;
val_one = val_one ^ val_two;

Now you can say that the first code is similar to the one presented later, then how is it not working, but the latter performs well?

A change in the order of these arithmetic operations can give different results. In the former code, val_one has an XOR with itself, thus having the result as 0.

In the latter, however, the order is defined already, and values are calculated perfectly, hence the difference.

However, remember not to use XOR swapping for higher code levels. It is unsafe and should be kept as a substitute.

Author: Bilal Shahid
Bilal Shahid avatar Bilal Shahid avatar

Hello, I am Bilal, a research enthusiast who tends to break and make code from scratch. I dwell deep into the latest issues faced by the developer community and provide answers and different solutions. Apart from that, I am just another normal developer with a laptop, a mug of coffee, some biscuits and a thick spectacle!

GitHub