I am using IComparable and a IComparer
In the Student class:[IComparable]
public int CompareTo(Student studentToCompare)
{
if (this.Number < studentToCompare.Number)
return 1;
else if (this.Number > studentToCompare.Number)
return -1;
else
return 0;
}
In the StudentCompareName class: [IComparer]
public int Compare(Student x, Student y)
{
return string.Compare(x.Name, y.Name);
}
With Compare(Student x, Student y) I am sorting the list of students on name.
If I dont use a CompareTo() in the Student-class, I'm getting errors.
I wonder why I need to have a CompareTo() in my main (Student) class, and what does it do? Why do I need to compare first the student number in the Student class and after that I'm allowed to sort on name in the StudentCompareName class?
I am using IComparable and a IComparer
That's the source of the confusion. You only need one of the two - and they'd rarely be implemented in the same class.
IComparable<T>
is implemented to give a natural comparison between one object and another. In the case of something like Student
, that probably doesn't make sense, as there are multiple ways to compare students. On the other hand, for something like DateTime
it makes perfect sense.
IComparer<T>
is meant to be a custom comparison - so it makes sense to have a StudentNameComparer
which implements IComparer<Student>
by comparing the names, for example.