I have dictionary based on a custom class. I am facing issues with overriding the GetHashCode() while inheriting IEquatable interface. My class object has three properties:
- Id1 (string)
- Id2 (string)
- Id3 (string)
I am retrieving data from two different sources and creating dictionaries out of these collections based on the above custom class. There are cases when one data source has two of the above ids populated whereas the other one only has one id populated. For example,
Collection1 = {Object{Id1 = null, Id2 = "NewId2", Id3 = "NewId3"}}
Collection2 = {Object{Id1 = null, Id2 = null, Id3 = "NewId3"}}
There are also cases where Id3 is null in collection2 but Id2 is not null. I am not sure how I would go about overriding GetHashCode() for such a case. I have already tried the if-elseif-else block, but there are edge cases where this logic fails:
if (Id3 != null)
{
return Id3.GetHashCode();
}
else if (Id2 != null) {
return Id2.GetHashCode();
}
else {
return Id1.GetHashCode();
}
No particular order seems to work in my case. For some more context, I am trying to use the TryGetValue method from a dictionary in .NET. I looked at the source code and saw that they are using GetHashCode() there to search by keys, which is how I traced by bug to this function. Does anyone know of a way to get around this issue?
Edit: adding some examples to clarify the correct behavior
Example 1
Object1 = Object1{Id1 = null, Id2 = "K2", Id3 = "K3"};
Object2 = Object2{Id1 = null, Id2 = null, Id3 = "K3"};
Answer: object1 == object2 because Id3 matches
Example 2
Object1 = Object1{Id1 = null, Id2 = "K2", Id3 = "K3"};
Object2 = Object2{Id1 = null, Id2 = "K2", Id3 = null};
Answer: object1 == object2 because Id2 matches
Example 3
Object1 = Object1{Id1 = "K1", Id2 = null, Id3 = "K3"};
Object2 = Object2{Id1 = "K1", Id2 = "K2", Id3 = null};
Answer: object1 == object2 because Id1 matches
Edit2: a match occurs when at least of the ids between two objects is equal. For the sake of discussion, assume the following hash code mapping,