Difference between IComparable and IComparer Interface in C#

CsharpProgrammingServer Side Programming

IComparable Interface in C#

Use the IComparable Interface in C# to sort elements. It is also used to compare the current instance with another object of same type.

It provides you with a method of comparing two objects of a particular type. Remember, while implementing the IComparable interface, CompareTo() method should also be implemented.

Let us see an example −

int IComparable.CompareTo(object ob) {
   Vehicle v=(Vehicle)ob;
   return String.Compare(this.make,v.make);
}

IComparer interface in C#

The IComparer interface is used to sort elements that compare two objects and provides additional comparison method.

Example

private class sortYearAscendingHelper : IComparer {
   int IComparer.Compare(object ob1, object ob2) {
      Vehicle v1=(Vehicle)ob1;
      Vehicle v2=(Vehicle)ob2;
      if (v1.year > v2.year)
      return 1;
      if (v1.year < v2.year)
      return -1;
      else
      return 0;
   }
}

Now return an instance of IComparer object.

public static IComparer sortYearAscending() {
   return (IComparer) new sortYearAscendingHelper();
}
raja
Published on 17-Sep-2018 08:41:34
Advertisements