r/ProgrammerTIL • u/qkrrmsp • Jun 21 '18
C# [C#]You can swap values of two variable with the new tuple syntax, without introducing a new temporary variable.
Instead of
var temp = a;
a = b;
b = temp;
you can now just do
(a, b) = (b, a);
89
Upvotes
22
u/qkrrmsp Jun 21 '18
Maybe this way it's ultimately using more memory by creating a temporary ValueTuple<int, int> instead of just one temporary int.
But I think the code is much more readable and cleaner with this new syntax.
7
u/Penguinfernal Jun 22 '18
You can also swap values without a temporary variable with some xoring. Not nearly as readable, but still cool imo.
a = a ^ b;
b = b ^ a;
a = a ^ b;
1
u/Crozzfire Jun 21 '18
very nice!
0
u/[deleted] Jun 21 '18
[deleted] — view deleted comment