FP S1210: Implementing comparable operators for private types

Rule S1210 suggests to implement the comparable operators, when implementing IComparable.

I fully agree with the reasoning of this rule. That begin said, for private (nested) classes/records/structs I would argue that this rule generates noise, instead of better code; those types are private because their usage is limited.

public class BaseClass
{
    private sealed class Entry(int n): IComparable<Entry> // FP, private classes should be minimal
    {
        private readonly int Value = n;
        public int CompareTo(Entry other) => Value.CompareTo(other.Value);
    }

    private sealed record Entry2(int Value): IComparable<Entry2> // FP, private records should             
    {
        private readonly int Value = n;
        public int CompareTo(Entry2 other) => Value.CompareTo(other.Value);
    }

    private readonly struct Entry3(int n): IComparable<Entry3> // FP, private classes should be minimal
    {
        private readonly int Value = n;
        public int CompareTo(Entry3 other) => Value.CompareTo(other.Value);
    }
}

Reported by SonarAnalyzer.CSharp v10.15.0.120848

Hello @Corniel

I agree with your arguing and created an (internal) ticket to track our work on such an exception. I added the following reasoning:

The rules is heavyweight and requires the user to implement 6 additional methods. Also, all collections that require “Compare” semantics, like ArrayList.Sort, SortedList, SortedSet, SortedDictionary do not require Equals or GetHashCode to work correctly.

Given that, an exception for the rule for a limited and tightly scoped set of types is reasonable.

1 Like