== vs. Object.Equals(object) in .NET

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

Leave a Comment