Why does SortedSet<T> ignore CompareTo() values of 0 by default?

When I try to AddRange to a SortedSet, it doesn't add values when their compareto result is zero. This doesn't make any sense to me, as it's not a SortedSet of the values that compareTo is comparing, it's a SortedSet of T. I am trying to understand why Microsoft would implement it like this.

  1. Is there any logical explanation to this that will help me remember in the future?
  2. Is the correct way to implement IComparable on my type by not returning 0 from CompareTo? What happens if I need CompareTo to determine equality explicitly when I use its IComparable.CompareTo() method elsewhere in my code?
Jon Skeet
people
quotationmark

The whole point of the comparison is to say whether one item is greater than, less than or equal to another. A set doesn't allow equal values - and in a sorted set, equality is defined by the comparison. It's as simple as that.

For your second question, it sounds like you want to have two different comparisons - one which returns 0 in certain cases where the other one wouldn't. You can do that by implementing IComparer<T> in a separate class, as the separate comparison. Just bear in mind that you'll still want to return 0 for Compare(x, x) for example, otherwise you'd never be able to find anything in the set other than by iterating over it...

people

See more on this question at Stackoverflow