How to Swap Two Numbers in C# (With and Without a Third Variable)

Two warehouse bin counts got keyed into the wrong slots, and you need to flip them. To swap two numbers in C#, write (a, b) = (b, a); or use a temp variable. Both are safe, and the tuple version fits on one line:

(binA, binB) = (binB, binA);

In this tutorial, I’ll compare every way to swap two numbers in C#: a temp variable, tuple deconstruction, the arithmetic and XOR tricks without a third variable, a generic Swap<T>, array elements and objects.

My running sample is two Dallas warehouse bins holding 340 and 125 units, and every output below comes from a real dotnet run on .NET 10.

Method 1: Swap Two Numbers in C# with a Temp Variable

This is the textbook version, and it’s still a fine default:

int binA = 340, binB = 125;   // Dallas warehouse bins
Console.WriteLine($"Before: binA = {binA}, binB = {binB}");

int temp = binA;
binA = binB;
binB = temp;

Console.WriteLine($"After:  binA = {binA}, binB = {binB}");

Output:

Before: binA = 340, binB = 125
After:  binA = 125, binB = 340
C# program to swap two numbers using a temp variable, TempSwap.cs code and output in VS Code
Swapping two bin counts with a temporary variable

How does this code work?

temp parks 340 before binA = binB overwrites it, then binB = temp puts it back. New to variables in C#? Start there.

Method 2: Swap with Tuple Deconstruction (a, b) = (b, a)

Since C# 7.0, the right side builds a tuple from the current values and the left side deconstructs it. It also rotates three values:

int binA = 340, binB = 125;
(binA, binB) = (binB, binA);
Console.WriteLine($"Bins:   binA = {binA}, binB = {binB}");

int austin = 18, denver = 22, boston = 15;
(austin, denver, boston) = (denver, boston, austin);
Console.WriteLine($"Rotate: austin = {austin}, denver = {denver}, boston = {boston}");

Output:

Bins:   binA = 125, binB = 340
Rotate: austin = 22, denver = 15, boston = 18
C# swap two numbers with tuple deconstruction (binA, binB) = (binB, binA) and a three-way rotate, output in VS Code
A tuple swap and a three-way rotate in one line each

How does this code work?

Both values on the right are read before anything on the left is assigned, so nothing gets overwritten halfway.

The compiler still creates temporaries for you; you just don’t write them. My tuple in C# guide covers deconstruction.

Pro Tip: This is what I write in new code. It’s short, it can’t overflow, and it works for any type, not just numbers.

Method 3: Swap Two Numbers Without a Third Variable Using Addition and Subtraction

This is the classic interview answer: store the sum, then subtract your way back. I also pushed it to int.MaxValue:

int binA = 340, binB = 125;
binA = binA + binB;
binB = binA - binB;
binA = binA - binB;
Console.WriteLine($"Small values: binA = {binA}, binB = {binB}");

int big = int.MaxValue, one = 1;
big = big + one;
Console.WriteLine($"Intermediate sum: {big}");
one = big - one;
big = big - one;
Console.WriteLine($"Unchecked: big = {big}, one = {one}");

try { int x = int.MaxValue; x = checked(x + 1); }
catch (OverflowException ex) { Console.WriteLine($"Checked: {ex.Message}"); }

Output:

Small values: binA = 125, binB = 340
Intermediate sum: -2147483648
Unchecked: big = 1, one = 2147483647
Checked: Arithmetic operation resulted in an overflow.
C# swap without third variable using addition and subtraction, int.MaxValue wraparound and checked OverflowException in VS Code
The arithmetic swap works for small values, wraps at int.MaxValue and throws in a checked context

How does this code work?

With int.MaxValue + 1, the sum wraps to -2147483648. C# integer math is unchecked by default, so it wraps back and the swap still lands by luck.

Turn on checked or the CheckForOverflowUnderflow setting, and the same line throws OverflowException. A try-catch block in C# can catch it, but the real fix is to skip this trick.

With double, the sum can lose digits, and the multiply-and-divide variant fails when a value is 0.

Method 4: Swap Two Numbers in C# with Bitwise XOR

XOR can’t overflow, but it has a different trap: swapping a value with itself.

int binA = 340, binB = 125;
binA ^= binB;
binB ^= binA;
binA ^= binB;
Console.WriteLine($"XOR swap: binA = {binA}, binB = {binB}");

int[] bins = { 340, 125 };
XorSwap(ref bins[0], ref bins[0]);   // i == j: same storage location
Console.WriteLine($"XOR with itself: bins[0] = {bins[0]}");

static void XorSwap(ref int x, ref int y)
{
    x ^= y;
    y ^= x;
    x ^= y;
}

Output:

XOR swap: binA = 125, binB = 340
XOR with itself: bins[0] = 0
C# XOR swap of two numbers and the same-variable trap where XorSwap(ref x, ref x) sets the value to 0, VS Code output
The XOR swap works on two variables but zeroes a value swapped with itself

How does this code work?

When both ref parameters point to the same element, the first line does x ^= x, which is 0, and 340 vanishes. Real sorts hit this when i == j.

Pro Tip: If you ever must use XOR, guard it with if (i != j). Better yet, use a tuple swap and skip the guard.

Method 5: Write a Generic Swap<T> Method with ref Parameters

When you swap in several places, put it in a method. The parameters need ref, because C# passes arguments by value.

int home = 98, away = 104;
Swap(ref home, ref away);
Console.WriteLine($"Scores: home = {home}, away = {away}");

string first = "Jenna Moore", second = "Ryan Carter";
Swap(ref first, ref second);
Console.WriteLine($"Shift:  first = {first}, second = {second}");

static void Swap<T>(ref T left, ref T right) => (left, right) = (right, left);

Output:

Scores: home = 104, away = 98
Shift:  first = Ryan Carter, second = Jenna Moore

How does this code work?

ref T makes both parameters aliases for the caller’s variables. See functions in C# if ref is new.

Pro Tip: You can’t pass a property to a ref parameter, because properties are methods, not variables. Use a tuple swap on properties instead.

How Do You Swap Two Elements in a C# Array or List?

The tuple syntax works on array elements and list indexers too. Here I move the top score of four US teams to the front:

int[] scores = { 72, 98, 104, 88 };
List<string> teams = ["Bulls", "Celtics", "Lakers", "Knicks"];

(scores[0], scores[2]) = (scores[2], scores[0]);
(teams[0], teams[2]) = (teams[2], teams[0]);

Console.WriteLine(string.Join(", ", scores));
Console.WriteLine(string.Join(", ", teams));

Output:

104, 98, 72, 88
Lakers, Celtics, Bulls, Knicks

That line is the core of most sorts, and you’ll reuse it to reverse an array in C# with two pointers. My C# array tutorial covers indexing.

Swap Strings and Objects (Reference Types) in C#

Swapping two class variables swaps the references, not the objects. Watch what happens inside a method:

var east = new Team("Celtics", 104);
var west = new Team("Lakers", 98);

TrySwap(east, west);
Console.WriteLine($"No ref:   east = {east.Name}, west = {west.Name}");

(east, west) = (west, east);
Console.WriteLine($"Tuple:    east = {east.Name}, west = {west.Name}");

static void TrySwap(Team x, Team y) => (x, y) = (y, x);

record Team(string Name, int Score);

Output:

No ref:   east = Celtics, west = Lakers
Tuple:    east = Lakers, west = Celtics

TrySwap got copies of the references, so its swap never reached the caller. Strings work the same way, which is why Method 5 needs ref for them too.

Why Do Interviewers Ask to Swap Without a Third Variable?

They’re testing assignment order, overflow and bitwise operators. It sits next to warm-ups like the C# program to add, subtract, multiply and divide two numbers.

My 2026 answer: show the arithmetic or XOR version, name its trap, then say you’d ship (a, b) = (b, a). More in these C# interview questions for experienced developers.

Things to Keep in Mind

  • “No third variable” tricks are harder to read, and I’ve never seen one make real code faster.
  • Arithmetic swaps throw under checked and lose precision with double.
  • XOR works only on integers and zeroes a value swapped with itself.
  • Inside a method, use ref, or you’re swapping copies.

Which Way to Swap Two Numbers in C# Should You Use?

MethodWorks forWatch out for
(a, b) = (b, a)Any type, arrays, listsNeeds C# 7.0 or later
Temp variableAny type, any C# versionOne extra line
Swap<T>(ref a, ref b)Reusable helperCan’t take properties
Addition/subtractionIntegers, interviewsOverflow in checked code
XORIntegers, interviewsSame variable becomes 0

My pick is the tuple swap everywhere. Want more number programs? Try these next:

Frequently Asked Questions

How do you swap two numbers in C#?

Use tuple deconstruction, (a, b) = (b, a);, or a temp variable: int temp = a; a = b; b = temp;. Both work for any values.

How do you swap two numbers in C# without a third variable?

Use (a, b) = (b, a). The interview tricks are a = a + b; b = a - b; a = a - b; and the XOR version a ^= b; b ^= a; a ^= b;.

Is the XOR swap faster than a temp variable in C#?

Not in any way you’d notice in normal code, and XOR adds the same-variable bug. Use the tuple swap.

Can the arithmetic swap overflow in C#?

Yes. a + b can exceed int.MaxValue. It wraps silently by default but throws in a checked context.

Which C# version supports (a, b) = (b, a)?

C# 7.0 and later, through tuples and deconstruction. See tuple types on Microsoft Learn.