Following sample code illustrate differences between IComparable and IComparer. It shows how to achieve the same thing by using these interefaces. The fist approach uses IComparable:
class IComparableTester
{
class Student:IComparable<Student>
{
string _Name;
int _OverallScore;
public Student(string name, int overallScore)
{
_Name = name;
_OverallScore = overallScore;
}
public string Name
{
get { return _Name; }
}
public int OverallScore
{
get { return _OverallScore; }
}
int IComparable<Student>.CompareTo(Student other)
{
return (this.OverallScore.CompareTo(other.OverallScore));
}
}
public void PrintSortedStudentList()
{
List<Student> studentList = new List<Student>();
studentList.Add(new Student(“Tom”, 80));
studentList.Add(new Student(“Ali”, 90));
studentList.Add(new Student(“Jeff”, 70));
studentList.Sort();
Console.WriteLine(“***** Use IComparable Interface *****”);
foreach (Student student in studentList)
{
Console.WriteLine(“Name:\t{0}\t OverallScore:\t{1}”,
student.Name, student.OverallScore);
}
}
}
The second class uses the IComparer interface to sort student list:
class IComparerTester
{
class StudentComparer: IComparer<Student>
{
int IComparer<Student>.Compare(Student a, Student b)
{
return a.OverallScore.CompareTo(b.OverallScore);
}
}
class Student
{
string _Name;
int _OverallScore;
public Student(string name, int overallScore)
{
_Name = name;
_OverallScore = overallScore;
}
public string Name
{
get { return _Name;}
}
public int OverallScore
{
get { return _OverallScore; }
}
}
public void PrintSortedStudentList()
{
List<Student> studentList = new List<Student>();
studentList.Add(new Student(“Tom”, 80));
studentList.Add(new Student(“Ali”, 90));
studentList.Add(new Student(“Jeff”, 70));
studentList.Sort(new StudentComparer());
Console.WriteLine(“***** Use IComparer Interface *****”);
foreach (Student student in studentList)
{
Console.WriteLine(“Name:\t{0}\t OverallScore:\t{1}”,
student.Name, student.OverallScore);
}
}
}
And the output from this console program shows that both works the same:
static void Main(string[] args)
{
IComparerTester tester1 = new IComparerTester();
tester1.PrintSortedStudentList();
IComparableTester tester2 = new IComparableTester();
tester2.PrintSortedStudentList();
Console.ReadKey();
}
