Skip to content

Support equality comparison delegate #2418

Closed
@jnm2

Description

@jnm2

This is already possible today:

Is.EqualTo(...).Using<Foo>((x, y) => x.CompareTo(y)))

The delegate returns int which allows you to pick one: equal, greater than, or less than. It's a sorting comparison rather than an equality comparison.

I have a similar scenario with objects in a third party library that provide IsEqual but do not override Equals (:thinking:...). This should work:

Is.EqualTo(...).Using<Foo>((x, y) => x.IsEqual(y)))

But because it returns bool rather than int, it does not work. I am forced to arbitrarily convert equal/inequal to either 0/1 (equal/greater than) or 0/-1 (equal/less than). I don't like this because an ordering comparison does not make sense in this context, only a pure equality comparison.

Is.EqualTo(...).Using<Foo>((x, y) => x.IsEqual(y) ? 0 : 1))

In my opinion, I should be able to return a bool directly from any arbitrary delegate and NUnit should use it like it uses bool IEqualityComparer<>.Equals similar to the effect of this final workaround:

private sealed class FooEqualityComparer : IEqualityComparer<Foo>
{
    public static FooEqualityComparer Instance { get; } = new FooEqualityComparer();
    private FooEqualityComparer() { }

    public bool Equals(Foo x, Foo y) => x.IsEqual(y);

    // I don't even want to think about implementing the hash code on this property bag.
    public int GetHashCode(Foo obj) => 0;
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions