comparer and comparable

  • Thread starter Thread starter Nick
  • Start date Start date
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
 
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.
 
Back
Top