Initializing an expression in C #

I have the following line of code

int i = (i = 20);

and it sets me to 20. Now my question is, are the two statements the same?

int a = 0;

int i = (a = 20);

and

int a = 0;

int i = a = 20;

Both operators will set the values ​​as i = 20and a = 20. Who cares?

If they are the same, then why are there bindings for equalizing the value?

+5
source share
4 answers

From MSDN :

Assignment operators are right-associative, which means that operations are grouped from right to left. For example, an expression of the form a = b = c evaluates to a = (b = c).

+10
source

Yes, these two are the same, but I would strongly discourage you from initializing variables like this. I would prefer:

int a = 0;
// Whatever the intervening code is

a = 20;
int i = a;
+7

?

. ,

int x = 2 + 2;

int x = (2 + 2);

.

?

. .

, unparenthesized, # . . myVar return (myVar)? .

, ?

. ?

, :

"int = (i = 20);"

, . , int i = x; , int i; i = x; , , int i; i = (i = 20);.

? (1) . ( . : http://blogs.msdn.com/b/ericlippert/archive/2010/02/11/chaining-simple-assignments-is-not-so-simple.aspx) (2), , , . ( , ).

+2

. - , .

. , . .

0
source

All Articles