comparer and comparable

N

Nick

Why do we have the IComparable and IComparer interfaces don't they do
the same thing (dispite having function which take in eitehr one and
two parameters respectivly). an you give an exaple of where I would
use one and not the other.

Thanks
Nick
 
J

Jon Skeet

Nick said:
Why do we have the IComparable and IComparer interfaces don't they do
the same thing (dispite having function which take in eitehr one and
two parameters respectivly). an you give an exaple of where I would
use one and not the other.

They don't do the same thing: IComparable says "I'm willing to be
compared with other things." IComparer says "I'm willing to compare two
things."

For instance, you might use IComparer to compare two strings by length,
whereas string itself implements IComparable to compare strings by
lexical order.

Basically, use IComparable to make it simple to (say) sort objects in
some kind of "default" way, and IComparer to sort objects usually of a
*different* class, in custom ways.
 

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