![]() |
C# provides an IComparable interface. This interface provides different types of type-specific comparison methods which means a value type or a class can implement this interface to sort its instances because we cannot sort the instances of a class directly because the compiler does not know on which basis to sort. Similarly comparing directly two instances will throw compiler error as the compiler gets confused about what to compare. Syntax:
Implementing IComparable Interface requires:
Now let us discuss how to implement the IComparable interface with the help of the below example. Example: Below is the implementation of the IComparable interface. in this example we sort the employees according to their employee ID. C#
Output: Before sorting employees array ID - 1, Employee Name - Susmita ID - 5, Employee Name - Soniya ID - 3, Employee Name - Rohit ID - 2, Employee Name - Mohit ID - 4, Employee Name - Pihu After sorting employees array ID - 1, Employee Name - Susmita ID - 2, Employee Name - Mohit ID - 3, Employee Name - Rohit ID - 4, Employee Name - Pihu ID - 5, Employee Name - Soniya |
Reffered: https://www.geeksforgeeks.org
C# |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |