Note that you are comparing object , not string !
It's right:
string c = new StringBuilder("hello").ToString(); string d = new StringBuilder("hello").ToString(); c == d;
or that:
var c = new StringBuilder("hello").ToString(); var d = new StringBuilder("hello").ToString(); c == d;
(because in this case var will implicitly enter variables as a result of StringBuilder.ToString() , which is equal to string ), see here for more information
Do not mix object and string comparisons.
In your base case, the comparison led to true, because it was actually the same object!
In the second case, you have two "new" operators, therefore, two different string builders that generate two new string objects. Not the same persistent string object.
The comparison used is determined by the type of your variables.
source share