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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,xbecomes1), then the comparison is done:0 == 0is 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,xbecomes1), 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.