Class that implements IComparable interface comes with only one member, CompareTo method. CompareTo method compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
In short we can compare two elements of the same collection and as a result we get int value that tells us relative order of the objects being compared.
We can also compare two instances of the same class and result tells us weather results are the same, first value is greater or less than compared value.
Example using non-generic IComparable interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>(); employees.Add(new Employee() {Id = 1, FirstName = "John", LastName = "Doe", IsFullTime = true}); employees.Add(new Employee() {Id = 2, FirstName = "Johny", LastName = "Doe", IsFullTime = true }); int compareResult = employees[0].CompareTo(employees[1]); Console.WriteLine(compareResult); // Result = -1 // return Less than zero if this object // is less than the object specified by the CompareTo method. // Result = 0 // return Zero if this object is equal to the object // specified by the CompareTo method. // Result = 1 // return Greater than zero if this object is greater than // the object specified by the CompareTo method. } } public class Employee : IComparable { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool IsFullTime { get; set; } public int CompareTo(object obj) { Employee employeeToCompare = (Employee)obj; return FirstName.CompareTo(employeeToCompare.FirstName); } } |
Example using generic IComparable interface:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>(); employees.Add(new Employee() {Id = 1, FirstName = "John", LastName = "Doe", IsFullTime = true}); employees.Add(new Employee() {Id = 2, FirstName = "Johny", LastName = "Doe", IsFullTime = true }); int compareResult = employees[0].CompareTo(employees[1]); Console.WriteLine(compareResult); } } public class Employee : IComparable<Employee> { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool IsFullTime { get; set; } public int CompareTo(Employee obj) { return FirstName.CompareTo(obj.FirstName); } } |
Difference between these two approaches:
- Using non-generic interface IComparable requires of us to cast obj to desired type.
- Generic interface IComparable<T> is type safe.