Object equality behaves different in .NET

.net, c#

Solution

string a = "abc"; 
string b = "abc"; 

Console.Writeline(a == b); //true 

String references are the same for the same string due to String Interning

object x = a; 
object y = b; 

Console.Writeline(x == y); // true 

Because the references are the same, two objects created from the same reference are also the same.

string c = new string(new char[] {'a','b','c'}); 
string d = new string(new char[] {'a','b','c'}); 

Here you create two NEW arrays of characters, these references are different.

Console.Writeline(c == d); // true 

Strings have overloaded == to compare by value.

object k = c; 
object m = d; 

Since the previous references are different, these objects are different.

Console.Writeline(k.Equals(m)) //true 

`.Equals` uses the overloaded String `equals` method, which again compare by value

Console.Writeline(k == m); // false 

Here 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.

Problem

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

Original source

Related problems