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 other was simply a personal preference. Over time, I'm come to find that these two are not the same thing, even in a default implementation (see this and this). To further confuse the matter, each can be overridden/overloaded separately to have completely different meanings.
Is this a good thing, what are the differences, and when/why should you use one over the other?
The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
The == operator compares whether two object references point to the same object.
Difference between == and . Equals method in 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With