They have a variety of uses, but perhaps the most common is in sorting an
ArrayList.
Suppose you have a class Dog, and an ArrayList, List, of Dogs. You wish to
sort List by ageOfDog. You would have Dog implement the interface
IComparable. The implementation would cast the parameter in the CompareTo
method to a Dog, and return a value based on how this.ageOfDog compared to
((Dog)(obj)).ageOfDog). Then to sort the List, you could just invoke
List.Sort().
But suppose in another part of the application you would like to sort the
same List by nameOfDog. You have already "used up" the IComparable
interface that Sort uses. So, you can either set up a new class that
inherits from IComparer, or (if this is the only additional sort you need),
have Dog implement the IComparer interface too.
Then in the Compare method, which has two parameters, you would cast each to
a Dog and return a value based upon how the nameOfDog compares. Then to
invoke a sort by nameOfDog you would just say List.Sort(this) (or
List.Sort(someObjectThatImplementsIComparer)).
So: use IComparable when you want one of the objects in the comparison to
handle the compare. Use IComparer when this is not feasible or desirable,
and either you need to let a third object handle the compare, or want to do
different compare logic than has been already been used by IComparable.
Sort is not the only method that uses these interfaces (e.g. BinarySearch).
You may wish to invoke them yourself if you write a general routine that
needs to compare objects but wish to leave the details of the comparison up
to another object.
"Cybertof" <cy****************@gmx.net> wrote in message
news:MP************************@msnews.microsoft.c om...
Hello,
Could someone please explain me the difference between the 2 interfaces
IComparable and IComparer ?
In which cases use one or the other ?
Are they dedicated to own classes or built-in collections ?
Regards,
Cybertof.