Swap two variables without using temporary variable in C#
This post will discuss how to swap two variables without using a temporary variable in C#.
1. Using Tuples
In C# 7.0 and later, you can swap values of two variables using the new tuple syntax, without introducing a temporary variable. C# supports deconstructing of tuples, which allows unpackaging all the items in a tuple in a single deconstruct operation, by assigning its elements to individual variables.
The following example shows how you can swap values of two variables with tuple deconstructing. Notice that the code is much more readable, concise, and cleaner with tuples.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int x = 1, y = 2; (x, y) = (y, x); Console.WriteLine("x={0}, y={1}", x, y); // x=2, y=1 } } |
2. Using temporary variable
Before C# 7.0, the only option to swap values of two variables is using a temporary variable. The following example provides an illustration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { int x = 1, y = 2; int temp = x; x = y; y = temp; Console.WriteLine("x={0}, y={1}", x, y); // x=2, y=1 } } |
You can create a static utility method for swapping two variables using the ref parameter. This will make your code readable and shows intent compared to the above solution.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
using System; public class Example { public static void Swap(ref int x, ref int y) { int temp = x; x = y; y = temp; } public static void Main() { int x = 1, y = 2; Swap(ref x, ref y); Console.WriteLine("x={0}, y={1}", x, y); // x=2, y=1 } } |
That’s all about swapping two variables without using a temporary variable in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)