Harsha
Harsha

Reputation: 1181

Initialization expression in c#

I have the following line of code

int i = (i = 20);

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

int a = 0;

int i = (a = 20);

and

int a = 0;

int i = a = 20;

Both the statements will set the values as i = 20 and a = 20. What's the difference?

If they are same then why are there braces for equating the value?

Upvotes: 5

Views: 1327

Answers (4)

Eric Lippert
Eric Lippert

Reputation: 659956

are the two statements same ?

Yes. Just as

int x = 2 + 2;

and

int x = (2 + 2);

are the same.

What's the difference?

There is no difference. They're the same.

There are some rare cases in which there should be a difference between a parenthesized and an unparenthesized expression, but the C# compiler actually is lenient and allows them. See Is there a difference between return myVar vs. return (myVar)? for some examples.

If they are same then why are there braces for equating the value?

I don't understand the question. Can you clarify the question?

A question you did not ask:

Why is it legal to say "int i = (i = 20);"

It is a strange thing to do, but legal. The specification states that int i = x; is to be treated the same as int i; i = x; So therefore this should be the same as int i; i = (i = 20);.

Why then is that legal? Because (1) the result of an assignment operator is the value that was assigned. (See my article on the subject for details: http://blogs.msdn.com/b/ericlippert/archive/2010/02/11/chaining-simple-assignments-is-not-so-simple.aspx) And (2) because the definite assignment checker ensures that the local variable is not written to before it is read from. (It is never read from in this case; it is written to twice.)

Upvotes: 3

C0L.PAN1C
C0L.PAN1C

Reputation: 12233

Order of Operations. When you put something in parenthesis it does that operation first.

And agreeing with the assignment of variables. It's better to do it vertically than horizontally. All on the same line can be confusing and more difficult with longer variables and assignments.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

Yes, those two are the same - but I would strongly discourage you from initializing variables like this. I would much rather see:

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

a = 20;
int i = a;

Upvotes: 7

sll
sll

Reputation: 62484

From MSDN:

The assignment operators are right-associative, meaning that operations are grouped from right to left. For example, an expression of the form a = b = c is evaluated as a = (b = c).

Upvotes: 11

Related Questions