Tuple Swap in C# : A Cleaner Way to Exchange Values
When we first learn C#, we often use a temporary variable to swap two values like this:
int temp = a;
a = b;
b = temp;
However, starting from C# 7.0, we can achieve the same result in a much cleaner way:
(a, b) = (b, a);
How does this work?
This is made possible by a feature called tuple deconstruction.
(a, b)
is a tuple on the left-hand side representing variables.(b, a)
is a tuple on the right-hand side representing values.
The right-hand tuple is evaluated first, and its values are temporarily held before being assigned to the left-hand variables. This allows for a clean and safe swap, without the need for a temp variable.
It works with list elements too
List<int> numbers = new List<int> { 5, 6, 4 };
(numbers[1], numbers[0]) = (numbers[0], numbers[1]);
This swaps numbers[0]
and numbers[1]
in a single, readable line.
When was this introduced?
Tuple deconstruction was introduced in C# 7.0, which was officially released in March 2017 alongside Visual Studio 2017. It brought many modern language features, and this syntax for value swapping was among the most immediately useful for everyday programming.
IDE Hints
Modern IDEs such as Visual Studio and JetBrains Rider will often give you a hint or warning (e.g., IDE0180
) if you use the old swapping style with a temp variable, recommending this tuple-based syntax instead.
Summary
C# has been evolving to offer cleaner and more expressive syntax. The tuple swap is a small but powerful example of how the language helps you write less code with greater clarity. If you haven’t used it yet, give it a try in your next project!