string s1 = "hi";
string s2 = "hi";
bool x = (s1 == s2);
Console.WriteLine(bool.Parse(""+x)); //printed as true and my point of interest
x = s1.Equals(s2);
Console.WriteLine(bool.Parse("" + x));//printed as true
s1 = s2;
x = (s1 == s2);
Console.WriteLine(bool.Parse("" + x));//printed as true
x = s1.Equals(s2);
Console.WriteLine(bool.Parse("" + x));//printed as true
Since s1==s2 compares references, it shoukd be returned as false. But i get the output as true. I observe this in case of strings alone. When this is done on objects of other classes, it rightly evaluates to false. Why is this exceptional behaviour observed in strings?
There are two things going on here.
The first is that the string type overloads the == operator. The reference comparison of the == operator is only the default behavior. Any type can overload that operator to get better semantics. If you want to guarantee reference equality, use the
ReferenceEquals()method.The second is something called interning, which allows two different string variables that have the same value to refer to the same object. Interning means that even without the overloaded == operator, if the “hi” literal is interned for both variables, the == and ReferenceEquals() comparisons could still return true