I have these statements and their’ results are near them.
string a = "abc";
string b = "abc";
Console.Writeline(a == b); //true
object x = a;
object y = b;
Console.Writeline(x == y); // true
string c = new string(new char[] {'a','b','c'});
string d = new string(new char[] {'a','b','c'});
Console.Writeline(c == d); // true
object k = c;
object m = d;
Console.Writeline(k.Equals(m)) //true
Console.Writeline(k == m); // false
Why the last equality gives me false ?
The question is why ( x == y ) is true ( k == m ) is false
String references are the same for the same string due to String Interning
Because the references are the same, two objects created from the same reference are also the same.
Here you create two NEW arrays of characters, these references are different.
Strings have overloaded == to compare by value.
Since the previous references are different, these objects are different.
.Equalsuses the overloaded Stringequalsmethod, which again compare by valueHere we check to see if the two references are the same… they are not
The key is figuring out when an equality is comparing references or values.
Objects, unless otherwise overloaded, compare references.
Structs, unless otherwise overloaded, compare values.