Connecting Tech Pros Worldwide Forums | Help | Site Map

IComparer vs. IComparable?

Brett Romero
Guest
 
Posts: n/a
#1: Sep 24 '06
What are the reasons to use one over the other?

SortedList implements IComparer.Compare(). Why would you also want to
create a SortedList class that implements IComparable.CompareTo()?

I know IComparable compares objects of the same type and IComparer
doesn't. Is that the main reason for using one over the other? So if
a SortedList contains objects all of Type A, I should implement
IComparable and not depend on the SortedList implementation of
IComparer? How does using the default implementation affect real world
results in anyway?

Thanks,
Brett


Jon Skeet [C# MVP]
Guest
 
Posts: n/a
#2: Sep 24 '06

re: IComparer vs. IComparable?


Brett Romero <account@cygen.comwrote:
Quote:
What are the reasons to use one over the other?
>
SortedList implements IComparer.Compare(). Why would you also want to
create a SortedList class that implements IComparable.CompareTo()?
>
I know IComparable compares objects of the same type and IComparer
doesn't. Is that the main reason for using one over the other? So if
a SortedList contains objects all of Type A, I should implement
IComparable and not depend on the SortedList implementation of
IComparer? How does using the default implementation affect real world
results in anyway?
IComparable is about a type saying, "I can be compared with something
else" (usually of the same type). IComparer is about a type saying "I
can compare two things".

Things tend to implement IComparable if there's a natural ordering for
the instance, whereas things tend to implement IComparer in order to
give an ordering for *other* types. For instance, String implements
IComparable itself, but if I wanted to sort strings primarily on their
length, I'd implement IComparer.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Closed Thread