I was going through few examples and came across below code:
(a, b) = (b, a);
It was mentioned that this can be used to swap the values of the two variables.
I tried it out as below:
int a = 5, b = 10;
Console.WriteLine(a + " " + b); // Prints --> 5 10
(b, a) = (a, b);
Console.WriteLine(a + " " + b); // Prints --> 10 5
What is this syntax? Is it something new or is this some weird trick to get the swapping result. Can it also be used with any number of variables.
Like:
(a, b, c) = (c, a, b); // a=c; b=a; c=b; or even more variables
It creates a tuple on the right hand side of the =
then deconstructs it (into different variables) on the left hand side. See this page of the fine manual
Effectively the compiler is writing something like this for you, if you're familiar with the Tuple<T1,T2> introduced years ago:
var t = new Tuple<int,int>(a, b); //create with Item1 = a and Item2 = b
b = t.Item1;
a = t.Item2;
Exactly what code it will be writing under the hood, I don't know, but that will be the spirit of it; to create a temporary (probably Value)Tuple, assign a and b to it then get them out again in the opposite order