Jace Rhea
Jace Rhea

Reputation: 5018

Method parameter assignment in C#

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

Answers (5)

Rod
Rod

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

a1ex07
a1ex07

Reputation: 37382

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

Upvotes: 4

Guffa
Guffa

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

James
James

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

bdukes
bdukes

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

Related Questions