2

Suppose I write the following code:

int x = 42;

if (x.Equals(x = Foo()))
    Console.WriteLine("ok");

Where Foo is any method returning an integer. Is it guaranteed that the method invocation target (the first x) is evaluated before it is replaced by the return value of Foo()? In other words, is this code guaranteed to print ok if and only if the return value of Foo() is equal to 42?

I've seen other questions that deal with the order of parameter evaluations, but they don't talk about when the instance (first x) gets evaluated during runtime for non-static methods -- could someone clarify this for me?

Thomas
  • 3,321
  • 1
  • 21
  • 44
  • Have you tried running this code? with `int Foo() { return 10; }` it prints `"ok"`, which means you're comparing `10` to `10`, not `42` to `10`. – MarcinJuraszek Mar 24 '14 at 07:36
  • 2
    @MarcinJuraszek I think he is asking if this is guaranteed by standard and not just "implementation specific" behavior. C++ is full of that. – Euphoric Mar 24 '14 at 07:37
  • @MarcinJuraszek As Euphoric says, I'm interested in what the C# spec has to say about it, whether it works on my implementation or not is not useful if I can't determine if it's even defined. – Thomas Mar 24 '14 at 07:41

3 Answers3

3

This is problem called Sequence Points. This is often represented what happens when you put increment operator inside an expression.

In case of C# it is strictly defined that expression and method parameters are evaluated from left to right, from inside out and that any assignment (and side effects in general) is immediately visible for the rest of the expression.

You can read more here.

Community
  • 1
  • 1
Euphoric
  • 12,645
  • 1
  • 30
  • 44
1

x = Foo() will be evaluated first, then x (the one on the left) will be referenced, therefore, this condition will be always true.

void Main()
{
    int x = 42;

if (x.Equals(x = Foo())) //This is always true.
    Console.WriteLine(x); //0
    Console.WriteLine("ok");
}

int Foo()
{
    return 0;
}
Ofiris
  • 6,047
  • 6
  • 35
  • 58
0

Foo() will get executed first, however I would write it like this:

int x = 42;

if (x == Foo()) {
    // ok
}

= will always assign

== will compare the two values

logikal
  • 1,123
  • 13
  • 26