VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-program-to-implement-icomparable-interface/

⇱ C# Program to Implement IComparable Interface - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# Program to Implement IComparable Interface

Last Updated : 18 Feb, 2022

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:

public interface IComparable

Implementing IComparable Interface requires:

  • Adding a method CompareTo() which receives an object and returns an integer.
  • The incoming object is first type-casted as the class type and stored in a temporary variable. It is then compared with a property of the current method
  • The CompareTo() method depending on the comparison:
    • returns 0, if the current instance's property is equal to the temporary variable's property
    • returns 1, if the current instance's property is greater than the temporary variable's property
    • returns -1, if the current instance's property is less than the temporary variable's property

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.

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
Comment
Article Tags:

Explore