Multiple inline assignments in one statement in c#

荒凉一梦 提交于 2019-12-11 02:19:44

问题


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;


来源:https://stackoverflow.com/questions/12040863/multiple-inline-assignments-in-one-statement-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!