IComparer vs. IComparable?

B

Brett Romero

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
 
J

Jon Skeet [C# MVP]

Brett Romero said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top