1

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?

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
jimbo
  • 603
  • 9
  • 27

1 Answers1

3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • You're right - and I have had that at one point, but it wasn't working either. The "Contains" method I am calling on an IEnumerable just doesn't seem to call to the "Equals" method on FilterViewModel. – jimbo Sep 16 '15 at 10:35
  • Edit: It has to be implemented at the exact level that it is used. So IEquatable will not work for a CustomerViewModel. – jimbo Sep 16 '15 at 10:57