Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

== vs Equals in C#

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
like image 350
Aditya Singh Avatar asked Oct 06 '10 10:10

Aditya Singh


People also ask

Are == and Equals same C#?

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.

Is Equals better than == in C#?

Answering to the point “There is no difference between equality comparison using “==” and “Equals()”, except when you are comparing “String” comparison. The common comparison Rule :-Whenever youare comparing variables they are either value types or reference types.

Which is faster Equals or ==?

Specifically with regard to strings, yes, == is slightly faster than equals , because the first thing the String.


1 Answers

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.

like image 128
Ben Voigt Avatar answered Sep 28 '22 02:09

Ben Voigt