From The name, this Interface used for comparison. This is the implementation of this interface:
|public interface IComparable |
int CompareTo(object o);
|Public Interface IComparable |
Function CompareTo(ByVal o As Object) As Integer
The result of this function is Integer; it returns 0 in similarity, -1 when the first one is smaller and 1 when larger .
Now we don't need to know who is larger, let’s assume that we have car class, something like that:
|Class Car |
Private Name As String
Private year As Integer
Now we need to sort the cars depends on the creation year, our first step it to implement IComparable interface.
Next, we should write an implementation to CompareTo function, something like that:
|int IComparable.CompareTo(object obj) |
Car temp = (Car)obj;
if(this.year > temp.year)
if(this.year < temp.year)
|Private Function CompareTo(ByVal obj As Object) As |
Integer Implements IComparable.CompareTo
Dim temp As Car = DirectCast(obj, Car)
If Me.year > temp.year Then
If Me.year < temp.year Then
Anyway, -1 is equals to -100 in return value, this function work with any negative number referring to smaller, any positive number also is accepted instead of 1.
Assume we have array of numbers, in this case some code like that is applicable.
But if we have array of cars, this will cause error, except if we implementing IComparable interface. in this case the array.sort() will use CompareTo function to sort all array elements. This is better solution than using another function for check and sorting. It is also more readable for people who work with you or read your code.