Difference between == and Equals() Method in C#
In C#, the equality operator == checks whether two operands are equal or not, and the Object.Equals() method checks whether the two object instances are equal or not.
Internally, == is implemented as the operator overloading method, so the result depends on how that method is overloaded. In the same way, Object.Equals()
method is a virtual method and the result depends on the implementation. For example, the == operator and .Equals()
compare the values of the two built-in value types variables. if both values are equal then returns true
; otherwise returns false
.
int i = 10, j = 10;
Console.WriteLine(i == j); // true
Console.WriteLine(i.Equals(j)); // true
For the reference type variables, == and .Equals()
method by default checks whether two two object instances are equal or not. However, for the string type, == and .Equals()
method are implemented to compare values instead of the instances.
string str1 = "Hello",
str2 = "Hello",
str3 = "hello";
Console.WriteLine(str1 == str2); // true
Console.WriteLine(str1 == str3 ); // false
Console.WriteLine(str1.Equals(str2));// true
Console.WriteLine(str1.Equals(str3));// false
Now, look at the following example:
object obj1 = "Hello";
object obj2 = "Hello";
Console.WriteLine(obj1 == obj2); // true
Console.WriteLine(obj1.Equals(obj2)); // true
In the above example, it looks like == and Equals()
method compares values. However, they compare instances. C# points two objects to the same memory address if both the values are equal. So, they return true
.
Now, check the following:
object obj1 = new StringBuilder("Hello");
object obj2 = "Hello";
Console.WriteLine(obj1 == obj2); // false
Console.WriteLine(obj1.Equals(obj2));// false
In the above example, obj1
points to StringBuilder type object and obj2
is string type, so both are different instances even if they have same values. So, == and Equals()
method compares the instances and return false
because they are different instances.