string s1 = "t";
string s2 = 't'.ToString();
Console.WriteLine(s1.Equals(s2)); // returning true
Console.WriteLine(object.Equals(s1, s2)); // returning true
Here it is returning same result. Now when I’m using StringBuilder it is not returning same value. What is the underneath reason?
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
Console.WriteLine(s1.Equals(s2)); // returning true
Console.WriteLine(object.Equals(s1, s2)); // returning false
Edit1: My above question answered below. But during this discussion what we find out StringBuilder doesn’t have any override Equals method in its implementation. So when we call StringBuilder.Equals it actually goes to Object.Equals. So if someone calls StringBuilder.Equals and S1.Equals(S2) the result will be different.
String.Equals() is overriden in C# such that identical strings are in fact
Equal()when theEqual()override defined onstringis used.If you are comparing string literals (not the case in your example), it’s worth noting that identical string literals are interned… that is, identical strings live at the same address so will also be equal by reference (e.g. object.Equals() or s1.ReferenceEquals(s2)) as well as by value.
StringBuilder provides an overload to
Equals()that takes StringBuilder as a parameter (that iss1.Equals(s2)will call that overload instead of callingobject.Equals(object obj)).http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.equals.aspx
StringBuilder.Equals() is…
object.Equals() uses the static Equals() defined on object, which checks only for reference equality (if passed a class) or for value equality (if passed a struct).
So in summary