Custom comparer of a SortedSet

SortedSet uses a custom comparer for sorting items. The comparer serves two purposes:

  1. define a criterion for ordering items in the set (e.g. the Length property in the sample below), AND
  2. identify duplicate items, so that only one is present in the Set.

Focusing on 1), it is easy to forget about 2), and then have calls to the Add() method of the SortedSet fail with new items that have a sorting property matching that of another item already in the set.
Quick fix: in the comparer, return the relation between the properties used for sorting, and if they match, pick another property of the class that is unique and can differentiate different objects (in the sample below, the Start property cannot be the same for objects with the same Length).

public class ByPatchLength : IComparer<Patch>
{
    public int Compare(Patch x, Patch y)
    {
        // if lengths are equal, the starting position will differentiate the patches
        if (y.Length == x.Length)
            return y.Start - x.Start;
        else
            return y.Length - x.Length;
    }
}