Swapping Variables In C# With ValueTuples
[C#, .NET]
In the preliminary stages of learning programming, you may have encountered this assignment.
You have two variables,
a
and b, such thata
is10
andb
is20
.Write a program that swaps the values.
Your first naive attempt almost certainly looked like this:
var a = 10;
var b = 30;
Console.WriteLine($"a is {a} and b is {b}");
a = b;
b = a;
Console.WriteLine($"a is {a} and b is {b}");
Which, of course, prints the wrong thing.
a is 10 and b is 30
a is 30 and b is 30
The correct solution would introduce an intermediate variable and look something like this:
var a = 10;
var b = 30;
Console.WriteLine($"a is {a} and b is {b}");
var temp = a;
a = b;
b = temp;
Console.WriteLine($"a is {a} and b is {b}");
This prints the following:
a is 10 and b is 30
a is 30 and b is 10
A creative solution to this problem is to utilize the ValueTuple.
var a = 10;
var b = 30;
Console.WriteLine($"a is {a} and b is {b}");
(a, b) = (b, a);
Console.WriteLine($"a is {a} and b is {b}");
The magic is taking place here:
(a, b) = (b, a);
Here we are creating a ValueTuple
on the left and then deconstructing the values on the right.
This will also run as expected.
a is 10 and b is 30
a is 30 and b is 10
TLDR
You can use ValueTuple
to swap variables.
Happy hacking!