Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CompareTo() method doesn't work

I have a Class named Person which implement IComparable<int> generic Interface . I have a generic list which contain Person Object and I assign my list to an array and I'm sorting the list but I'm taking the follwing error.

error: {"Failed to compare two elements in the array."}

this is my Person class

public class Person : IComparable<int> 
    {
        public int Age { get; set; }

        public int CompareTo(int other)
        {
            return Age.CompareTo(other);
        }
    }

and this program cs

class Program
{
    static void Main(string[] args)
    {
        List<Person> list2 = new List<Person>();

        list2.Add(new Person() { Age = 80 });
        list2.Add(new Person() { Age = 45 });
        list2.Add(new Person() { Age = 3 });
        list2.Add(new Person() { Age = 77 });
        list2.Add(new Person() { Age = 45 });

        Person[] array = list2.ToArray();
        Array.Sort(array);

        foreach (Person item in array)
        {
            Console.WriteLine(item.Age);
        }

        Console.ReadKey();
    }
}
like image 339
erhan urun Avatar asked Dec 05 '25 13:12

erhan urun


1 Answers

Change your class to this:

public class Person : IComparable<Person> 
{
    public int Age { get; set; }

    public int CompareTo(Person other)
    {
        return Age.CompareTo(other.Age);
    }
}

If you create class with IComperable<int> you are able to compare it with int, not with the same class. You have to pass to the template the same class/struct as one you are comparing with.

like image 82
Paweł Reszka Avatar answered Dec 11 '25 09:12

Paweł Reszka