skip to content

In C#, why does (a, b) = (b, a) swap two variables correctly when a = b; b = a; does not?

level: juniorimportance: should knowfreq 50%

answer

  1. assignment into existing variables
  2. read everything before writing
  3. targets located first
  4. works on array elements

basics

~10 s

(a, b) = (b, a) is a deconstructing assignment: C# reads both right-hand values before writing either target, so neither old value is lost. The two-statement version overwrites a before reading it back.

solid answer

~40 s

`(a, b) = (b, a)` is a **deconstructing assignment** into existing variables. C# first locates the targets on the left (evaluating any array or index expressions), then evaluates every value on the right, here the current `b` and `a`, and only then stores them from left to right, so no value is overwritten before it is read. `a = b; b = a;` fails because the first statement replaces `a` before the second reads it, leaving both equal to the old `b`. The same form swaps array elements, `(shelf[0], shelf[2]) = (shelf[2], shelf[0])`, rotates three values, or advances a pair as in `(prev, curr) = (curr, prev + curr)`. It needs no hand-written temporary, and for two locals the compiler emits IL that reads both values and stores them back, without building a `ValueTuple`.

code

csharp · 23 lines
csharp
using System;

int a = 1, b = 2;
(a, b) = (b, a);                              // swap: right side read before any write
Console.WriteLine($"{a} {b}");

int[] shelf = [10, 20, 30];
(shelf[0], shelf[2]) = (shelf[2], shelf[0]);  // works on array elements too
Console.WriteLine(string.Join(",", shelf));

int x = 1, y = 2;
x = y; y = x;                                 // naive swap loses the old x
Console.WriteLine($"{x} {y}");

int i = 0;
int[] slots = [0, 0];
(i, slots[i]) = (1, 5);                       // slots[i] is located while i is still 0
Console.WriteLine($"{i} {slots[0]} {slots[1]}");

int prev = 0, curr = 1;
for (int n = 0; n < 5; n++)
    (prev, curr) = (curr, prev + curr);       // Fibonacci step without a temp
Console.WriteLine(curr);

go deeper

for a junior

Recall that (a, b) = (b, a) swaps two variables because both right-hand values are read before anything is assigned.

for a middle

Explain the evaluation order: targets located first, right-hand values next, stores last, and show it working on array elements and settable properties.

for a senior

Spot evaluation-order traps such as (i, slots[i]) in review, and know the swap costs no heap allocation, so it needs no micro-optimised replacement.

for a principal

Use the tuple swap as the team idiom over hand-written temporaries or arithmetic tricks, and keep clever multi-target deconstructions out of shared code.

## The bug in the two-statement swap Swapping two variables is the first place many C# developers meet tuples. The naive version loses a value: ```csharp int a = 1, b = 2; a = b; // a is now 2; the old 1 is gone b = a; // b reads the new a, so b is 2 as well ``` Each statement runs completely before the next starts, so the second statement reads a value the first one already replaced. The classic fix is a temporary variable: `var tmp = a; a = b; b = tmp;`. ## What `(a, b) = (b, a)` means Since C# 7, a parenthesized list of existing variables can be the target of an assignment from a tuple. That is a **deconstructing assignment**: each position on the right is assigned to the same position on the left. The compiler evaluates it in three steps: 1. **Locate the targets** on the left, from left to right. For a plain local nothing needs evaluating; for `shelf[i]` the array reference and the index are evaluated now. 2. **Evaluate the right-hand values**, from left to right. For `(b, a)` that reads the current `b` and the current `a`. 3. **Store** each value into its target, from left to right. Because step 2 finishes before step 3 begins, both old values are captured before anything is overwritten. A logging run on the .NET 10 SDK shows the order directly: target expressions print first, then right-hand values, then the stores happen. ## Beyond two locals The same assignment works on any **assignable** target, as long as each position's value converts to the target's type: - **Array elements:** `(shelf[0], shelf[2]) = (shelf[2], shelf[0]);` - **Fields and settable properties:** `(box.A, box.B) = (box.B, box.A);` calls each getter, then each setter. - **More than two values:** `(a, b, c) = (b, c, a);` rotates three variables. - **Computed pairs:** `(prev, curr) = (curr, prev + curr);` advances a Fibonacci pair, because `prev + curr` uses the old values. - **Mixed declarations:** since C# 10 one deconstruction can assign existing variables and declare new ones, as in `(x, var y) = (1, 2)`. A target that cannot be assigned, such as a get-only property, fails to compile with the usual assignment error. ## Evaluation order with indexes Step 1 matters when a target's index depends on another target: ```csharp int i = 0; int[] slots = [0, 0]; (i, slots[i]) = (1, 5); // i == 1, slots == [5, 0] ``` `slots[i]` is located while `i` is still `0`, so the `5` lands in `slots[0]` even though `i` becomes `1` in the same statement. Code like this is legal but hard to read; a review should usually split it. ## What it costs | Way to swap | Lines | Extra storage | Handles any type | |---|---|---|---| | Temporary variable | 3 | one local | yes | | `(a, b) = (b, a)` | 1 | none you declare | yes | | A generic helper taking two `ref` parameters | 1 at the call site | inside the helper | yes | `ValueTuple` is a struct, so a tuple swap never puts an object on the heap. For two locals, the IL the compiler emits for `(a, b) = (b, a)` loads both values and then stores them back, using the evaluation stack or its own temporaries; no `ValueTuple` is constructed at all. The tuple form is idiomatic C#, not a performance compromise. A `ref`-parameter helper is covered with by-reference parameters and adds nothing here. ## When interviewers push further - They may ask what the expression's own value is: `var r = ((a, b) = (3, 4));` gives `r` the tuple `(3, 4)`. - They may ask whether a swap through a struct-returning property sticks; that is a question about struct copies, covered in the lesson on copying versus sharing. - They may ask about swapping with arithmetic or XOR tricks; in C# they suit only some numeric types, risk overflow or lost precision, and are never clearer than the tuple form.

  • In C#, with i = 0, what does `(i, slots[i]) = (1, 5)` leave in slots?
    `slots[0]` becomes 5 and `i` becomes 1. The target `slots[i]` is located, index included, before any value is stored, so the index uses the old `i`. Legal, but split it in real code.
  • Does a C# tuple swap of two locals allocate or build a ValueTuple?
    No heap allocation is possible, because `ValueTuple` is a struct. For two locals the compiler goes further: the emitted IL loads both values and stores them back, constructing no `ValueTuple` at all.
  • Can you swap two properties of an object with the C# tuple form?
    Yes, when both have accessible setters: `(box.A, box.B) = (box.B, box.A)` calls both getters first, then both setters. A get-only property as a target does not compile.

Swapping what two people hold: if one hands over first and then takes back, the first item is gone. The tuple swap is both people holding out their items at once, and only then does each take the other's.

  • (a, b) = (b, a) allocates a tuple object on the heap.
  • The tuple swap assigns a = b first, so it has the same bug.
  • Tuple swaps only work on local variables, not array elements.
  • C# needs a ref-based Swap helper to exchange two values.
  • A swap with tuples needs a named tuple type declared first.