CodexBloom - Programming Q&A Platform

advanced patterns with Dictionary<TKey, TValue> when Using Custom Equality Comparer in C# - scenarios to Find Keys

πŸ‘€ Views: 59 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
c# dictionary equality-comparer collections C#

I'm trying to configure I need help solving I'm stuck trying to I'm working with an scenario when using a custom equality comparer with `Dictionary<TKey, TValue>` in C#. I've implemented a comparer for a class `Person` based on the `Id` property, which is a unique identifier. The dictionary should allow me to retrieve `Person` objects by their `Id`, but I'm getting unexpected results. Specifically, when I attempt to retrieve a `Person` by its `Id`, it returns `null` instead of the expected object. Here's my `Person` class and the custom comparer: ```csharp public class Person { public int Id { get; set; } public string Name { get; set; } } public class PersonComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { return x.Id == y.Id; } public int GetHashCode(Person obj) { return obj.Id.GetHashCode(); } } ``` I then instantiated the dictionary like so: ```csharp var people = new Dictionary<Person, string>(new PersonComparer()); people.Add(new Person { Id = 1, Name = "Alice" }, "Developer"); ``` When trying to retrieve Alice using her `Id`, I use this code: ```csharp var keyToFind = new Person { Id = 1 }; // New instance with same Id if (people.TryGetValue(keyToFind, out var role)) { Console.WriteLine(role); // Expected: "Developer" } else { Console.WriteLine("Key not found"); } ``` This prints "Key not found" which is not what I expected. I've verified that the `Id` is indeed the same. I suspect it has something to do with how the dictionary handles object references, but I can’t seem to pinpoint the scenario. Is there something I'm missing with how I’m defining equality or the hash code? I’ve also tried overriding `GetHashCode` to return a constant, but that hasn't solved the question. Any assistance would be appreciated. Is there a better approach? For context: I'm using C# on CentOS. How would you solve this? This issue appeared after updating to C# 3.11.