StephenCleary / Comparers

The last comparison library you'll ever need!
MIT License
427 stars 33 forks source link

Use for comparing by interface? #40

Open rwv37 opened 6 months ago

rwv37 commented 6 months ago

I just tried using this library on a little stub of a class:

    internal sealed class PortCategory(string name) : ComparableBase<IPortCategory>, IPortCategory
    {
        static PortCategory()
        {
            DefaultComparer = ComparerBuilder.For<IPortCategory>()
                .OrderBy(x => x.Name);
        }

        public string Name { get; } = name ?? throw new ArgumentNullException(nameof(name));
    }

That fails compilation, with:

The type 'Rwv37.FreeBSD.VestertopianPortsBuilder.Core.Interfaces.IPortCategory' cannot be used as type parameter 'T' in the generic type or method 'ComparableBase<T>'. There is no implicit reference conversion from 'Rwv37.FreeBSD.VestertopianPortsBuilder.Core.Interfaces.IPortCategory' to 'Nito.Comparers.ComparableBase<Rwv37.FreeBSD.VestertopianPortsBuilder.Core.Interfaces.IPortCategory>'.

I then noticed that the sample in the docs implements ComparableBase of the class itself, and after looking at the source code it, it looks to me that this is required (?).

If I change ComparableBase<IPortCategory> to ComparableBase<PortCategory>, the compiler error goes away, but it's replaced by others, because PortCategory no longer implements IPortCategory (due to IPortCategory being both IComparable<IPortCategory> and IEquatable<IPortCategory>).

Of course in the case of this little stub class, it might be reasonable to just get rid of IPortCategory entirely, but that doesn't seem like it's necessarily a good solution in other, presumably more complex, cases.

Is there a way to use this library to do what I was hoping to do here? Thanks in advance.