Reputation: 59
I want to assign values to multiple variables at the same time. I know how it works in python but I need a equivalent for C#.
I found out that if I want to assign a value to a new variable I can do it like this.
int a = 1 , b = 1;
//This works fine but now I need to set the variables again
a = b , b = a + b;
//But i can't do it like that
//I know that in python it would look like this (a , b = b , a+b)
Upvotes: 0
Views: 530
Reputation: 39
I dont know if I got you right, but is this what you are looking for?
static void Main(string[] args)
{
int a = 1, b = 1;
a = b = (a + b);
Console.WriteLine($"{a} {b}");
Console.ReadKey();
}
Upvotes: 0
Reputation: 42235
This is valid C#, using tuples introduced in C# 7:
int (a, b) = (1, 2);
(a, b) = (b, a + b);
I wouldn't say this is idiomatic C# - I've never seen it in the wild, and I don't think many people know that you can do this - but it's valid.
The compiler doesn't actually use the ValueTuple class to do this - it synthesises the following code:
int a = 1;
int b = 2;
int temp1 = b;
int temp2 = a + b;
a = temp1;
b = temp2;
Upvotes: 5