I'm making my own comparer, and for that overwriting the equals and GetHashCode .
Basically I'm comparing a list of values, and if all items in the list are equal I return true. But if the list is empty, or if an item in the list is empty string, I want to return false.
That is simple enough to do, but I'm wondering how to reflect this in the GetHashCode function? Since GetHashCode does not compare the items, but just generates a value from a single item it seems impossible to have two different hashcodes when I want the objects to not be equal.
How much does it matter that objects that are not equal have the same hashcode?
An example of what I have right now:
public class CustomComparer : IEqualityComparer<Dictionary<string, string>>
{
List<string> keysToCompare = new List<string>();
public bool Equals(Dictionary<string, string> d1, Dictionary<string, string> d2)
{
if (keysToCompare.Count == 0) return false;
bool equals = true;
foreach(string key in keysToCompare)
{
equals &= !string.IsNullOrWhiteSpace(d1[key]);
equals &= d1[key].Equals(d2[key]);
}
return equals;
}
public int GetHashCode(Dictionary<string, string> d)
{
int hash = 3049;
int prime = 31;
foreach(string key in keysToCompare)
{
hash = hash * prime + d[key].GetHashCode();
}
return hash;
}
}