What is the difference between a.Equals(b) and a == b?
For value types, “==” and Equals() works same way : Compare two objects by VALUE
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True
For reference types, both works differently :
“==” compares REFERENCE – returns true if and only if both references point to the SAME object.
Equals method compares object by VALUE.
StringBuilder sb1 = new StringBuilder(”Mahesh”);
StringBuilder sb2 = new StringBuilder(”Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True
String s1 = “zzz”;
String s2 = “zzz”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
Why? Does that mean String a Value Type?
No, String IS a Reference Type. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example: