IComparable <T> defines a type-specific comparison method that can be used to organize or sort objects.
IEquatable <T> defines a generic method that can be used to determine equality.
Let's say you have a Person class
public class Person { public string Name { get; set; } public int Age { get; set; } } Person p1 = new Person() { Name = "Person 1", Age = 34 }; Person p2 = new Person() { Name = "Person 2", Age = 31 }; Person p3 = new Person() { Name = "Person 3", Age = 33 }; Person p4 = new Person() { Name = "Person 4", Age = 26 }; List<Person> people = new List<Person> { p1, p2, p3, p4 };
You can use people.Sort(); to sort these objects people.Sort(); ,
But it will be an exception.

Framework does not know how to sort these objects. You must tell how to sort the implementation of the IComparable interface.
public class Person : IComparable { public string Name { get; set; } public int Age { get; set; } public int CompareTo(object obj) { Person otherPerson = obj as Person; if (otherPerson == null) { throw new ArgumentNullException(); } else { return Age.CompareTo(otherPerson.Age); } } }
This will allow you to sort the array correctly using the Sort() method.
Further for comparison of two objects you can use the Equals() method.
var newPerson = new Person() { Name = "Person 1", Age = 34 }; var newPersonIsPerson1 = newPerson.Equals(p1);
This will return false because the Equals method does not know how to compare two objects. Therefore, you need to implement the IEquatable interface and tell the platform how to conduct the comparison. Continuing the previous example, it will look like this.
public class Person : IComparable, IEquatable<Person> { //Some code hidden public bool Equals(Person other) { if (Age == other.Age && Name == other.Name) { return true; } else { return false; } } }
Nipuna Apr 28 '19 at 13:07 on 2019-04-28 13:07
source share