I have a domain model that is trivially represented by the following.
IMyInterface
ClassA : IMyInterface
ClassB : IMyInterface
What I want is to implement IEquatable in such a way that I can write code something like.
if(dynamicallyCreatedInstanceOfClassA == dynamicallyCreatedinstanceOfClassB)
{
// Do something relevant
}
My first inclination was to have IMyInterface implement IEquatable but of course I can't actually do the implementing in IMyInterface. I would have to do that in ClassA and ClassB. What strikes me as wrong with this solution is that the implementations of IEquatable in ClassA and ClassB will be exactly, line for line the same. Is there an elegant way to accomplish this? When ClassC comes along I don't want to have to copy and past 50 lines of duplicated IEquatable code.
I have considered using an abstract base class instead of an interface, but in this scenario IMyInterface really just describes actions the class will perform and not what the class is. ClassA and ClassB don't share many similarities except they can both perform the actions in the IMyInterface contract.
Any insights are helpful, and thank you for your time.
GetHashCode
. Jon's approach is the only easy way out it seems.. – BeebeIEqualityComparer<T>
to represent rather broad forms of equivalence whichT
may know nothing about. For example, two objects that happen to implementIList<T>
should probably only report themselves as equal to each other if they will always contain the same items in the same order. It may be useful, however, for an object to be able to store lists that it owns into aDictionary<IList<T>,whaever>
, where lists containing the same items in any sequence will compare identical. – HygieneIList<T>
; implementations generally don't provide one either. Nonetheless, such a comparison method may be useful in some contexts, so it would be perfectly reasonable to use an outside class to implement anICEqualityComparer<IList<T>>
in such fashion. – Hygiene