views:

208

answers:

4

Hi, in the example below, what would 'foo' be set to each time? I've searched online but I can't find anywhere that gives me the answer:

static void Main(string[] args) {
   static public bool abc = true;
   static public bool foo = (abc = false);
   foo = (abc = true);
}
+2  A: 

Use == instead of = for boolean expressions.

Aviad P.
Mm, I was wondering if assignments returned boolean values, though.
Motig
@Motig: Assignments return the assigned value.
OregonGhost
+6  A: 

false the first time and true the second time. Remember that = is the assignment operator: it assigns the value of the second operand to the first, and then returns this value. For example:

int foo = 1;
int bar = (foo = 2);

The second line here assigns the 2 to foo, then returns 2 to the other assignment operator, which assigns 2 to bar. At the end of it all, both foo and bar have the value 2.

Edit: This is why it's valid to chain up assignment operations; e.g.

int foo;
int bar;
foo = bar = 2; // Equivalent to foo = (bar = 2);
Will Vousden
So assignment operations return the right hand side of the = sign?
Motig
@Motig: Yep, that's right.
Will Vousden
@Zakalwe Thank you!
Motig
This lack of clarity is exactly why it can be a bad idea to use return values from assignments in real code.
Joe
No, the comment above is incorrect, thought the answer is correct. The simple assignment operation does NOT return the right hand side! Assignment operation returns the *value that was assigned to the left hand side*. That might be *different* than the right hand side. For example, "long x; int y = 10; object z = (x = y);" assigns the *long* 10 to z, not the *int* 10.
Eric Lippert
Good catch. I was wondering whether it was worth being pedantic but ended up deciding it probably didn't matter.
Will Vousden
A: 

Your static variable definitions should be placed at the class level, not inside a method. In that case the intializers will be run in the order they are defined in the source code.

This means that abc will first be set to true, then foo will be set to false since abc is true.

Rune Grimstad
+2  A: 
  1. abc = true
  2. abc = false. Then foo = false
  3. abc = true. Then foo = true
Victor Hurdugaci