How to implement guide with overriding equals and gethashcode in a value type struct in c#
I'm working on a project and hit a roadblock. I'm working with unexpected behavior when I override `Equals` and `GetHashCode` in a struct that's supposed to represent a complex value type. The struct is used as a key in a `Dictionary`, but I'm getting duplicate keys that seem to arise from inconsistencies in hash code generation. Hereβs the struct definition: ```csharp public struct Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public override bool Equals(object obj) { if (obj is Point p) { return X == p.X && Y == p.Y; } return false; } public override int GetHashCode() { return HashCode.Combine(X, Y); } } ``` Iβm using this struct in a dictionary like so: ```csharp var points = new Dictionary<Point, string>(); points[new Point(1, 2)] = "A"; points[new Point(1, 2)] = "B"; // This should overwrite "A" ``` However, when I check the dictionary, both entries are present instead of just one. Iβm also getting the following warning when I try to debug: `Warning: Unhandled exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.` I've confirmed that the `X` and `Y` values are indeed the same for both `Point(1, 2)` instances. I suspect there might be some scenario with how the hash codes are being calculated or how Iβm using the struct, but Iβm not sure what else to look for. I tried implementing the `IEquatable<Point>` interface, but the scenario continues. Has anyone faced a similar question, or can someone explain what I might be missing? Has anyone else encountered this?