Trying to understand the GetHashCode()

c#, hashcode, object, oop

Solution

A simple observation based on the pigeonhole principle:

- `GetHashCode` returns an `int` - a 32 bit integer.

- There are 4.294.967.296 32-bit integers;

- Considering only uppercase English letters, there are 141.167.095.653.376 ten letter words. If we include upper- and lowercase, then we have 144.555.105.949.057.024 combinations.

- Since there are more objects than available hash-codes, some (different) objects must have the same hash code.

Another, more real-world example, is that if you wanted to give each person on Earth a hashcode, you would have collisions, since we have more persons than 32-bit integers.

"Fun" fact: because of the birthday paradox, in a city of 100.000 people, you have more than 50% chance of a hash collision.

Problem

I found the following on Microsoft documentation: ``` Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash code ``` I made my own tests to understand the Method: ``` public static void HashMetod() { List<Cliente> listClientTest = new List<Cliente> { new Cliente { ID = 1, name = "Marcos", Phones = "2222"} }; List<Empresa> CompanyList = new List<Empresa> { new Empresa { ID = 1, name = "NovaQuimica", Clients = listClientTest }, new Empresa { ID = 1, name = "NovaQuimica", Clients = listClientTest } }; CompanyList.Add(CompanyList[0]); foreach (var item in CompanyList) { Console.WriteLine("Hash code = {0}", item.GetHashCode()); } Console.WriteLine("CompanyList[0].Equals(CompanyList[1]) = {0}", CompanyList[0].Equals(CompanyList[1])); Console.WriteLine("CompanyList[0].Equals(CompanyList[2]) = {0}", CompanyList[0].Equals(CompanyList[2])); } ``` My Question is: How can two Differents objects returns the same HashCode? I believe that if two objects return the same, they are Equals(Thats what my method shows). Execute my method and check this out.

Original source