Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

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?

like image 675
Matthew Scharley Avatar asked Sep 22 '08 00:09

Matthew Scharley


People also ask

What is the difference between == object Equals ()?

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.

Can you use == with objects?

The == operator compares whether two object references point to the same object.

What is the difference between == and Equals () in C#?

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.

Which is better Equals or == 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.


1 Answers

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 
like image 133
molasses Avatar answered Oct 20 '22 00:10

molasses