So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the oth
Two of the most often used types, String and Int32, implement both operator==() and Equals() as value equality (instead of reference equality). I think one can consider these two defining examples, so my conclusion is that both have identical meanings. If Microsoft states otherwise, I think they are intentionally causing confusion.
string x = "hello";
string y = String.Copy(x);
string z = "hello";
To test if x
points to the same object as y
:
(object)x == (object)y // false
x.ReferenceEquals(y) // false
x.ReferenceEquals(z) // true (because x and z are both constants they
// will point to the same location in memory)
To test if x
has the same string value as y
:
x == y // true
x == z // true
x.Equals(y) // true
y == "hello" // true
Note that this is different to Java.
In Java the ==
operator is not overloaded so a common mistake in Java is:
y == "hello" // false (y is not the same object as "hello")
For string comparison in Java you need to always use .equals()
y.equals("hello") // true
My understanding of the uses of both was this: use == for conceptual equality (in context, do these two arguments mean the same thing?), and .Equals for concrete equality (are these two arguments in actual fact the exact same object?).
Edit: Kevin Sheffield's linked article does a better job of explaining value vs. reference equality…