== vs Equals in C#

2019-02-06 04:07发布

What is the difference between the evaluation of == and Equals in C#?

For Ex,

if(x==x++)//Always returns true

but

if(x.Equals(x++))//Always returns false 

Edited:

     int x=0;
     int y=0;

     if(x.Equals(y++))// Returns True

2条回答
淡お忘
2楼-- · 2019-02-06 04:44

Order of evaluation. ++ evaluates first (second example). But in the first example, == executes first.

查看更多
我只想做你的唯一
3楼-- · 2019-02-06 04:47

According to the specification, this is expected behavior.

The behavior of the first is governed by section 7.3 of the spec:

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

Thus in x==x++, first the left operand is evaluated (0), then the right-hand is evaluated (0, x becomes 1), then the comparison is done: 0 == 0 is true.

The behavior of the second is governed by section 7.5.5:

  • If M is an instance function member declared in a value-type:
    • E is evaluated. If this evaluation causes an exception, then no further steps are executed.
    • If E is not classified as a variable, then a temporary local variable of E’s type is created and the value of E is assigned to that variable. E is then reclassified as a reference to that temporary local variable. The temporary variable is accessible as this within M, but not in any other way. Thus, only when E is a true variable is it possible for the caller to observe the changes that M makes to this.
    • The argument list is evaluated as described in §7.5.1.
    • M is invoked. The variable referenced by E becomes the variable referenced by this.

Note that value types are passed by reference to their own methods.

Thus in x.Equals(x++), first the target is evaluated (E is x, a variable), then the arguments are evaluated (0, x becomes 1), then the comparison is done: x.Equals(0) is false.

EDIT: I also wanted to give credit to dtb's now-retracted comment, posted while the question was closed. I think he was saying the same thing, but with the length limitation on comments he wasn't able to express it fully.

查看更多
登录 后发表回答