The following code is available:
public class Fish { private readonly string name; public Fish(string name) { this.name = name; } public override int GetHashCode() { return name.GetHashCode(); } public override bool Equals(object obj) { var otherFish = obj as Fish; if (otherFish == null) { return false; } return otherFish.name == name; } } class Program { static void Main() { var duplicates = new Hashtable(); var key1 = new Fish("Herring"); var key2 = new Fish("Herring"); var key3 = new Fish("Herring2"); duplicates[key1] = "Hello"; duplicates[key2] = "Hello2"; duplicates[key3] = "Hello3"; Console.WriteLine(duplicates.Count); // Delay. Console.ReadKey(); } } When calling duplicates[key1] = "Hello" and duplicates[key3] = "Hello3" , only GetHashCode () is called, and when calling duplicates[key2] = "Hello3" , Equals () is called. How does the compiler determine when to call Equals () and when there is no need for it?
"Herring"which has already been added with the line above - that’s their hash codes matched, so Equals volunteered - tym32167