I have A and B classes both implementing interface I.
public interface I
{
int SomeInt { get; }
bool SomeBool { get; }
float SomeFloat { get; }
}
public class A : I
{
public int SomeInt { get; }
public bool SomeBool { get; }
public float SomeFloat { get; }
private readonly string _someARelatedStuff;
// Rest of class...
}
public class B : I
{
public int SomeInt { get; }
public bool SomeBool { get; }
public float SomeFloat { get; }
private string readonly _someBRelatedStuff;
private double readonly _someOtherBRelatedStuff;
// Rest of class...
}
Sometimes I want to test equality between A and B (usually when comparing lists of A and lists of B) based on the equality of their I properties (SomeInt, SomeBool, SomeFloat), so I implemented IEquatable<I> on both and I compare them based on their shared I properties values.
The problem is that I already have an implementation for GetHashCode() on both A and B that produces different hashes because I'm taking into account additional members.
B does not depend on A so I use interface I to compare them and it has a list of properties with getters.
I read in a StackOverflow answer that:
If you are implementing a class, you should always make sure that two equal objects have the same hashcode.
So does that mean that everytime a class A want to be implement interface I, and I want to be able to compare instances that implement I, I have to make sure the hashcode is calculated in the same way for all instances of I and only use I properties?
I do feel like I'm not intended to implement IEquatable<T> when T is an interface, but my alternatives are:
- Using regular inheritance with a base class - I rather avoid inheritance when possible, and this solution won't work if B needs to derive from some framework
Cclass because of single inheritance - Implement equality checks between
AandBwith a method on eitherAorB- will create code duplication - Have an equality check method between
Iinstances defined inI- sounds like the best option
Are there any options that I'm missing?