Reputation: 5018
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)
{
}
}
Upvotes: 3
Views: 891
Reputation: 55882
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
.
Upvotes: 1
Reputation: 700910
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
.
Upvotes: 6
Reputation: 5642
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.
Upvotes: 0
Reputation: 156065
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
.
Upvotes: 3