This blog is subject the DISCLAIMER below.

Tuesday, June 17, 2008

IComparable Interface.

From The name, this Interface used for comparison. This is the implementation of this interface:

C#:

public interface IComparable
{
int CompareTo(object o);
}

 

vb.net:

Public Interface IComparable
    Function CompareTo(ByVal o As Object) As Integer
End Interface

 

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:

C#:

class Car
{

string Name;
int year;
}

vb.net:

Class Car
    Private Name As String
    Private year As Integer
End Class

 

Now we need to sort the cars depends on the creation year, our first step it to implement IComparable interface.

C#:

class Car:IComparable
{

string Name;
int year;
}


vb.net:

class Car:IComparable
{

string Name;
int year;
}

 

Next, we should write an implementation to CompareTo function, something like that:

c#:

int IComparable.CompareTo(object obj)
{
Car temp = (Car)obj;
if(this.year > temp.year)
return 1;
if(this.year < temp.year)
return -1;
else
return 0;
}

 

vb.net:

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
        Return 1
    End If
    If Me.year < temp.year Then
        Return -1
    Else
        Return 0
    End If
End Function

 

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.

Sort Function:

Assume we have array of numbers, in this case some code like that is applicable.

c#:

Array.Sort(myNumbers);

 

vb.net:

Array.Sort(myNumbers)

 

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.

No comments: