What is the difference between a == b
and a.Equals(b)
?
String a = "toto".Substring(0, 4);
String b = "toto";
Object aAsObj = a;
Assert.IsTrue(a.Equals(b));
Assert.IsTrue(a == b);
Assert.IsFalse(aAsObj == b);
Assert.IsTrue(aAsObj.Equals(b));
This test pass in .NET, the trick is that Equals
is a method, whereas ==
is a static
method, so aAsObj == b
use
static bool Object.operator==(object a, object b) //Reference comparison
whereas a == b
use
static bool String.operator==(string a, string b) //String comparison
but a.Equals(b)
or aAsObj.Equals(b)
always use :
bool String.Equals(Object obj) //String comparison