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

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...