This question is taken from the book .NET interview questions written by Shivprasadkoirala and published by BPB publications.
“IComparable” interface helps to implement custom sorting for collections in c#. Let us try to understand the same with a simple c# example. For instance let’s say you have a list collection of people names as shown in the below code.
Now if you run the above program you will see that we have not applied sort on the collection. It displays data as they were inserted.
But now if you call “Peoples.Sort()” method on the collection you will get the following sorted output on the “name” value in ascending position.
But now let’s say that we need the person’s age also to be added in the list with the person name value. So logically you will create a “Person” class with “name” and “age” property as shown in the code below.
Once you create the class you would create an object of the person class and add it to the list collection as shown in the below code snippet.
But if you now try to call the “Sort” method on the List , he gets confused ?. On which value should he sort on “Name” or “Age” ?.
If you run the application it will throw up the below exception text. The exception text says that he is confused and he needs specific direction on how the sorting should work. This direction can be provided by using “IComparable” interface.
So in order to show a proper direction for the sort logic we need to implement “IComparable” interface as shown in the below. The logic of “Sort” needs to be defined in the “CompareTo” method.
You can see in the “CompareTo” method we have defined the logic saying if the “age” value is same then sort by using the “name” value or else use “age” value for sorting. If you run the application you would get the following output. You can see for “40” and “30” value he has sorted on the basis “Age” but for the remaining people the age is same so he sorted on the “Name” value.
So the use of “IComparable” interface is to define custom sorting logic on a collection.
For further c# interview preparation you can go through the following articles
Huge collection of c# interview question videos: – c# interview question videos .
Read this article on how to prepare for c# interviews: – c# interview questions and answers
Huge collection of c# and .NET interview question videos: – c# and .NET interview question videos.