- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between IComparable and IComparer Interface in C#
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(); }
Advertisements