I have a class:
public class Customer :IComparable<Customer>
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
I also have a List:
Customer cust = new Customer() { Id=10,Name="Jack",Salary= 15000};
Customer cust1 = new Customer() { Id = 10, Name = "Abby", Salary = 5000 };
Customer cust2 = new Customer() { Id = 10, Name = "Zed", Salary = 152000 };
List<Customer> CustomerList = new List<Customer>();
list.Add(cust);
list.Add(cust1);
list.Add(cust2);
CustomerList.Sort();
I understand why list.Sort wont work on Customer since Customer class has three properties and it does not know how to sort it. But if I implement the interface IComparable
in Customer
class I am able to sort the Customer List any way i want.
public class Customer :IComparable<Customer>
{
public int Id { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int CompareTo(Customer other)
{
return this.Salary.CompareTo(other.Salary);
}
}
Now my question is.. How does implementing CompareTo method let me sort CustomerList
? I am not even overriding Sort Method or anything.
I am confused since I have not used CompareTo method at all.
I read https://stackoverflow.com/a/4188041/2064292 but it does not answer my question.