Multiple inline assignments in one statement in c#

2019-07-21 19:03发布

问题:

Obviously the following is totally fine in c#;

int a;
int b = a = 2;

Is it possible to do multiple variable assignments in c# in a single statement?

i.e. something like;

int a = (int b = 2);

回答1:

If we look at:

int a;
int b = a = 2;

That is essentially a=2; then b=a; (but without an extra eval). So we can get similar by reversing the order:

int a = 2, b = a;

However: I would say take this a bit hesitantly: please also prioritise readability.



回答2:

Not as far as I know. The only variation I know of is:

int a = 2, b = 2;


回答3:

Probably as close as you're going to get.

int a, b = a = 2;

Console.WriteLine(a.ToString()); // 2
Console.WriteLine(b.ToString()); // 2


回答4:

You mean this?

int a = 2, b = 2;

Works fine



回答5:

No but you can do

int a = 2, b = a;

Here a will be initialized and then b will be initialized with value same of a.

or

int a, b = 2;

or

int a = 2, b = 2;

or as you said

int a = b = 2;