Custom IEqualityComparer implementation?

I have a custom class and want to put objects of this class in MutableHashSet. Can I implement custom equality comparer for automatically check the equality? (Dictionaries seem to use it too for example)

looks like I can just implement custom Equals operation! And it’s working, nice!

But it isn’t working with hashset because of IEqualityComparer implementation

изображение

Upd: works with GetHashCode implementation

изображение

Yes, you have to override both, GetHashCode and Equals.

But a word of warning from personal experience, overriding those operations can lead to hard to track down bugs (for example in your case you should be sure that your instances don’t mutate over time) or performance issues (using a constant “leaf” as the hash code will cancel out all the optimizations you usually gain from a dictionary or hash set). So usually it’s safer to explicitly setup a custom equality comparer (we have a region for that even, called Create [CustomEqualityComparer]) you then feed to the Create operation of your HashSet, Dictionary etc. That way reasoning about a patch is usually simpler - one can immediately see that the used equality is different on that hash set but at all other call sites (like a Cache region or a Changed node) we know it’s still the default reference equality.

1 Like

This is how you can set up a dictionary or hash set. The key is the create CustomEqualityComparer region. Also note, as Elias said, it is important to return a hash code, otherwise there is no performance gain from the Dictionary or HashSet because all elements would fight for the same hash location, and all work would be done by the Equals method. Equals should only ba a fallback when two elements return the same hash code:

image

1 Like

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.