7

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?

Community
  • 1
  • 1
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
  • 3
    Interesting theoretical question, but horrible idea to code this way in practice. If you do, please include a link to this question for those that have to maintain the code in the future. – Eric J. Aug 27 '12 at 19:30
  • The question should be closed because, as pointed out in some answers, it's a duplicate of multiple questions. – Tipx Aug 27 '12 at 19:43
  • Might not be a duplicate. My question specifically refers to the evaluation order of named argument passing. (The linked question doesn't obviously address my concern.) – Thomas Eding Aug 28 '12 at 17:33

3 Answers3

9

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.

Community
  • 1
  • 1
Pete Baughman
  • 2,996
  • 2
  • 19
  • 33
2

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
L.B
  • 114,136
  • 19
  • 178
  • 224
1

According to the C# In Depth – Optional Parameters and Named Arguments:

...The second of these calls reverses the order of the arguments, but the result is still the same, because the arguments are matched up with the parameters by name, not position.

In your case first will be executed y and after x, as it appears first (from the left) in the function declaration.

The fact that it's really ends up like a second parameter, is an implementation detail of C# compiler that implements named parameters.

Tigran
  • 61,654
  • 8
  • 86
  • 123