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
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
Order of evaluation. ++ evaluates first (second example). But in the first example, == executes first.
According to the specification, this is expected behavior.
The behavior of the first is governed by section 7.3 of the spec:
Thus in
x==x++
, first the left operand is evaluated (0
), then the right-hand is evaluated (0
,x
becomes1
), then the comparison is done:0 == 0
is true.The behavior of the second is governed by section 7.5.5:
Note that value types are passed by reference to their own methods.
Thus in
x.Equals(x++)
, first the target is evaluated (E isx
, a variable), then the arguments are evaluated (0
,x
becomes1
), 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.