For Value Type
== and .Equals() method usually compare two objects by value.
int a = 10;
int b = 10;
Console.WriteLine(a == b); // True
Console.WriteLine(a.Equals(b)); // True
For Reference Type
== performs an identity comparison, i.e. it will only return true if both references point to the same object.
While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.
StringBuilder s1 = new StringBuilder(“NO”);
StringBuilder s2 = new StringBuilder(“NO”);
Console.WriteLine(s1 == s2); // False
Console.WriteLine(s1.Equals(s2)); // True
In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Type use “==” operator, and use “Equals()” method while performing value comparison with Reference Type.
== and .Equals() method usually compare two objects by value.
int a = 10;
int b = 10;
Console.WriteLine(a == b); // True
Console.WriteLine(a.Equals(b)); // True
For Reference Type
== performs an identity comparison, i.e. it will only return true if both references point to the same object.
While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.
StringBuilder s1 = new StringBuilder(“NO”);
StringBuilder s2 = new StringBuilder(“NO”);
Console.WriteLine(s1 == s2); // False
Console.WriteLine(s1.Equals(s2)); // True
In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.
When to use “==” operator and when to use “.Equals()” method?
For value comparison, with Value Type use “==” operator, and use “Equals()” method while performing value comparison with Reference Type.