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.

Download  Run Code

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.

Download  Run Code

 
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.

Download  Run Code

That’s all about swapping two variables without using a temporary variable in C#.