Search code examples
c#iequalitycomparer

IEqualityComparer<T> not working for 'Contains' method


Okay, so I have the following classes/interfaces

FilterFileViewModel, CategoryViewModel, IFilterViewModel, ICategoryViewModel.

Inheritance is set up as follows:

IFilterViewMode : IEqualityComparer<IFilterViewModel>
ICategoryViewModel : IFilterViewModel
FilterViewModel : ViewModel, IFilterViewModel
CategoryViewModel :FilterViewModel, ICategoryViewModel

And I have implemented IEqualityComparer in the abstract class FilterViewModel.

Now, I have an IEnumerable<ICategoryViewModel>, but if I call "Contains" on it, it doesn't seem to use the Equals method I have implemented at FilterViewModel.

I can see that it's most likely because ICategoryViewModel doesn't have the Equals method... so the only solution I can think of is to have a collection of IEnumerable<CategoryViewModel> instead, but this isn't ideal.

Can anyone think of a better way to structure this?


Solution

  • You seem to misunderstand the purpose of IEqualityComparer<IFilterViewModel> interface. It is not common to implement it in your model objects. Rather, you implement it in a special helper class, and use it to tweak the interpretation of equality in situations when you need that. This is usually done in situations when you have no control over the Equals method of the class.

    If you want classes themselves to know how to compare for equality, you need to override Equals and GetHashCode methods on the classes themselves. If you want to force subclasses to supply type-specific Equals, use IEquatable<T> interface:

    IFilterViewMode : IEquatable<IFilterViewModel>
    

    Note: Don't forget to implement GetHashCode even if your current code path does not require it.