views:

99

answers:

5

Given the below code, will the method parameter y in Bar(int y) be assigned the value from x or 1? I realize they are logically equivalent, but I want to understand the assignment operation.

class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();
        var x = 0;
        foo.Bar(x = 1);
    }
}

public class Foo
{
    public void Bar(int y)
    {
    }
}
+4  A: 

It's assigned to the result of x=1 which equals 1.

a1ex07
+3  A: 

The result of the assignment operator will be passed to Bar, which "is the value that was assigned to the left-hand side" (from Eric Lippert's blog).

In this case, that is the int value 1.

bdukes
A: 

Anything inside the () will be passed to y, so long as its an int.

But I think to directly answer the question, x is what actually gets passed, not 1, x is equal to 1, to then y=x=1.

James
The result of the assignment gets passed, not the value of `x`.
bdukes
+3  A: 

The parameter gets the value of the assignment.

Consider code like this:

int x = 0;
int y = (x = 1);
x = 42;
foo.Bar(y);

Eventhough x is changed another time, y still contains 1.

Guffa
All good answers, but I found this the most clear and concise. Marked as answer.
Jace Rhea
+1  A: 

You have to consider the order of evaluation. Before calling a function, any expression, within the braces need to be evaluated. The result is then used as an argument in the function call.

In your case, the x = 1 is an expression. It needs to be evaluated to an assignment first (x=1) then you can use the resulting value which is x and use it as an argument to bar.

It is equivalent to

x = 1
foo.bar(x)

You can see that it will be evaluated if you look at the value of x after the call to foo.

Rod