Introduction
IComparable provides a method of comparing two objects of a particular type. This is necessary if we want to provide any ordering for our object. It defines an interface for an object with a CompareTo() method that returns an integer.
So, we could say that it provides a comparer check (for sorting) when there is only one way of ordering the objects (implemented inside the class)
IComparer, on the other hand, allows you to define and use multiple comparer checks (implemented outside the class)
It defines an interface with a Compare() method that takes two objects of another type (which don't have to implement IComparable) and
compares them.
Step 1
Add a class Student
- public class Student
- {
- public int Roll_number;
- public string Name;
- public int Grade;
- }
Step 2
- public class Student_Collection
- {
- public static void Main()
- {
- Student s1 = new Student() { Roll_number = 1, Name = "Avijit", Grade = 90 };
- Student s2 = new Student() { Roll_number = 3, Name = "Tirtha", Grade = 70 };
- Student s3 = new Student() { Roll_number = 2, Name = "Rajiv", Grade = 60 };
- Student s4 = new Student() { Roll_number = 4, Name = "Monosriz", Grade = 80 };
- List<Student> list = new List<Student>() { s1, s2, s3,s4 };
- list.Sort();
- foreach (var student in list)
- Console.WriteLine("Roll Number : " + student.Roll_number + " " + "Name : " + student.Name + " " + "Grade : " + student.Grade);
- Console.ReadLine();
- }
- }
Note
We would get an exception while calling the Sort() method since we are trying to sort a complex type hereStudent and the compiler does not understand on which attribute it should sort the list.
But if the list had been an integer type then we might have not encountered the exception, since the list would have contained all integer values which are nothing but scalar values.
Solution
Use the IComparable interface for sorting Complex Type, it has CompareTo() method as a member as discussed. Say that we have type Student and want to compare two objects from this type according to their Roll_number. It would be more practical to implement the IComparable interface within the Student class.
Modify your existing Student Class, adding the IComparable interface and implementing the CompareTo() Method in it.
- public class Student : IComparable<Student>
- {
- public int Roll_number;
- public string Name;
- public int Grade;
- public int CompareTo(Student other)
- {
- if (this.Roll_number > other.Roll_number)
- return 1;
- else if (this.Roll_number < other.Roll_number)
- return -1;
- else
- return 0;
- }
- }

Join the conversation! Your thoughts help the community grow.