0

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
  • Don't forget that in situations like these, it's easy to just run the code and check. Commented Jan 7, 2010 at 11:01
  • The place you want to search for is section 7.16.1 of the specification. Commented Jan 7, 2010 at 18:34

4 Answers 4

8

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);
Sign up to request clarification or add additional context in comments.

4 Comments

So assignment operations return the right hand side of the = sign?
This lack of clarity is exactly why it can be a bad idea to use return values from assignments in real code.
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.
Good catch. I was wondering whether it was worth being pedantic but ended up deciding it probably didn't matter.
2

Use == instead of = for boolean expressions.

2 Comments

Mm, I was wondering if assignments returned boolean values, though.
@Motig: Assignments return the assigned value.
2
  1. abc = true
  2. abc = false. Then foo = false
  3. abc = true. Then foo = true

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.