Search code examples
c#interfaceequalityiequatable

IEquatable<'1> on interface


So, I've got a interface for entities that requires them to expose their identity.

public interface IEntity<TIdentity> {
    public TIdentity Id { get; } 
}

Now I need to be able to compare two entities which each other, but I can't rely on the default implementations of Equals and GetHashCode because entities should be compared by their identity, and not overall signature. Since every class that implements IEntity<'1> should be comparable, I thought about declaring IEquatable<'1> directly on the entity interface.

Well.. that doesn't work. When I declare IEquatable<'1> on IEntity<'1> the interface enforces implementing classes to implement the following:

public bool Equals(IEntity<'1> other)

instead of

public bool Equals(TypeImplementingIEntity other)

So upon calling Equals on two entities, the runtime refers back to Equals(object obj) because the type of the argument on the method provided by IEquatable<'1> does not match the actual type! What do?


Solution

  • It should work. Equals(IEntity<TIdentity>) should take precedence over Equals(object)

    You should override Equals(object) anyway:

    public override bool Equals(object other) {
        return Equals(other as IEntity<TIdentity>);
    }