By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,959 Members | 2,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,959 IT Pros & Developers. It's quick & easy.

IComparer vs. IComparable?

P: n/a
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

Sep 24 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Brett Romero <ac*****@cygen.comwrote:
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 - <sk***@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
Sep 24 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.