The documentation for Sort says that Sort will throw an ArgumentException if ‘The implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself.’
Apart from the example given, can anyone tell me when this would otherwise happen?
The sort algorithm (QuickSort) relies on a predictable IComparer implementation. After a few dozen layers of indirection in the BCL you end up at this method:
Going a bit further into the QuickSort implementation, you see code like this:
Basically if the IComparer misbehaves the Quicksort call with throw an IndexOutOfRangeException, which is wrapped in n ArgumentException.
Here is another example of bad IComparer’s
So I guess, the short answer is, anytime your IComparer implementation does not consistently compare values as defined in the documentation: