I was trying to figure out a way to use a Dictionary to distinguish between unique combinations of pairs and accidentally realized that hashcodes for classes are generated differently than hashcodes for structs.
Consider this code:
Code:
class C
{
public string a { set; get; }
public string b { set; get; }
}
struct S
{
public string a { set; get; }
public string b { set; get; }
}
Console.WriteLine(new C{ a = "ab", b = "cd" }.GetHashCode());
Console.WriteLine(new C{ a = "ab", b = "cd" }.GetHashCode());
Console.WriteLine(new S{ a = "ab", b = "cd" }.GetHashCode());
Console.WriteLine(new S{ a = "ab", b = "cd" }.GetHashCode());
if you run code similar to the one above, you'll notice that the two instances of the struct have the same hashcode, but the two instances of the class have a different hashcode.
Can someone tell me how the hashcode is generated and why two instances of the same struct with the same properties have the same hashcode but the same is not true for two instances of the same class with the same properties?