Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation order of named parameters [duplicate]

Possible Duplicate:
Are parameters evaluated in order when passed into a method?

Say I have

void foo (int x, int y)

and call it by:

foo(y: genNum(), x: genNum())

Does C# guarantee the evaluation order of x and y in this case?

like image 934
Thomas Eding Avatar asked Aug 27 '12 19:08

Thomas Eding


2 Answers

According to the specification, arguments are always evaluated from left to right. Unfortunately, there are a few bugs in some corner cases in C# 4.0. See Eric Lippert's post at Are parameters evaluated in order when passed into a method? for more details.

As an aside, this is probably bad practice. If you want to guarantee the order that the arguments are evaluated, capture the result in a local variable first and then pass the results to the consuming method like:

int capturedY = genNum(); //It is important that Y is generated before X!
int capturedX = genNum();
foo(capturedX, capturedY);

I can't think of a good reason to not do it that way.

like image 146
Pete Baughman Avatar answered Sep 23 '22 09:09

Pete Baughman


This is not an answer, Just to show the side effect.

public void Test()
{
    foo(y: genNum(), x: genNum());
}

int X=0;
int genNum()
{
    return ++X;
}

void foo(int x, int y)
{
    Console.WriteLine(x);
    Console.WriteLine(y);
}

OUTPUT:

2
1
like image 26
L.B Avatar answered Sep 23 '22 09:09

L.B