Failed to compare two elements in the array in C#

When you want to use the Sort method of the List<T> (without parameters) , you should be implementing the IComparable<T> interface.

If you don’t implement the IComparable interface and you use the Sort method of the List<T> , you will end up getting the below error

Failed to compare two elements in the array.

This is a System.InvalidOperationException with the message “{System.InvalidOperationException: Failed to compare two elements in the array. -“.

The InnerException would indicate the following

{System.ArgumentException: At least one object must implement IComparable.
   at System.Collections.Comparer.Compare(Object a, Object b)
   at System.Collections.Generic.ObjectComparer`1.Compare(T x, T y)

image

So , when you get this error. Go back to Your C# class and implement the IComparable interface to get the Sort method working.

Leave a Reply