Reader Level:
ARTICLE

Using IComparable and IComparer to compare objects in VB.NET

Posted by Bechir Bejaoui Articles | Visual Basic .NET November 10, 2012
The .Net framework and especially the System.Collection namespace provides us two built in interfaces witch are IComparable and IComparer interfaces in order to compare two objects.
  • 0
  • 0
  • 10797

The .Net framework and especially the System.Collection namespace provides us two built in interfaces witch are IComparable and IComparer interfaces. The first one, namely, the IComparable specifies a behavior that allows an object to be compared to another one from the same type according to a specified member value such as a hash table value or so. At the other hand, IComparer interface enables us to compare two objects at once at the opposite of the first one witch enables us to compare two objects one by one. The IComparable and the IComparer could also be found as a part of the System.Collection. Generic built in interfaces, thing that renders the deal more comfortable when using them since the conversion exceptions headache will be neutralized and avoided with generic types.     

In this article I will try to provide some techniques according to the effective use of the IComparable and the IComparer interfaces in a development context and I will expose some real use cases to know how, and under witch condition may one use each of both interfaces.

IComparable interface

Public Interface IComparable

        ' Methods

        Function CompareTo(ByVal obj As ObjectAs Integer

End Interface


The IComparable interface has Function CompareTo (ByVal as Object) as Integer as a member. This last one is used to compare two objects one by one profiting of the extreme polymorphism nature of the interface. Say, that we have a type person and you want to compare two objects from this type according to their ages for example. It will be more practical to implement the IComparable interface within the person class core.

Public Class Person

    Implements IComparable

    ' Methods

    Public Sub New()

    End Sub

 

    Public Sub New(ByVal FirstName As StringByVal LastName As StringByVal AgeAs Integer)

        Me.FirstName = FirstName

        Me.LastName = LastName

        Me.Age = Age

    End Sub

 

    Public Function CompareTo(ByVal o As ObjectAs Integer

        Dim Temp As Person

        Temp = CType(o, Person)

        If (Me.Age < o.Age) Then

            Return 1

        End If

        If (Me.Age > o.Age) Then

            Return -1

        End If

        Return 0

    End Function

 

 

    ' Properties

    Public Property Age As Integer

        Get

            Return Me._Age

        End Get

        Set(ByVal value As Integer)

            Me._Age = value

        End Set

    End Property

 

    Public Property FirstName As String

        Get

            Return Me._FirstName

        End Get

        Set(ByVal value As String)

            Me._FirstName = value

        End Set

    End Property

 

    Public Property LastName As String

        Get

            Return Me._LastName

        End Get

        Set(ByVal value As String)

            Me._LastName = value

        End Set

    End Property

 

 

    ' Fields

    Private _Age As Integer

    Private _FirstName As String

    Private _LastName As String

End Class   

The method Function CompareTo (ByVal as Object) as Integer returns an integer. You can specify your result according to the returned value as follow:

Class Program

    ' Methods

    Public Shared Sub Main(ByVal args As String())

        Console.WriteLine("Hello World!")

        Dim I As New Person("Bejaoui""Bechir", &H1D)

        Dim myFather As New Person("Habib""Bejaoui", &H41)

        Dim myGrandFather As New Person("Krayem""Bejaoui", &H5F)

        Select Case [I].CompareTo(myFather)

            Case 1

                Console.WriteLine("My father is older than me")

                Exit Select

            Case -1

                Console.WriteLine("I'm older than my father!!!")

                Exit Select

            Case 0

                Console.WriteLine("My Father and I have the same age!")

                Exit Select

        End Select

        Console.Write("Press any key to continue . . . ")

        Console.ReadKey(True)

    End Sub

 

End Class

 

When the generics come into the world as a part of the .Net 2.0 innovations, the code structure becomes more robust as the problem that may raise a casting exception is avoided in this case. So the person class code structure will be as following:

Public Class Person

    Implements IComparable(Of Person)

    ' Methods

    Public Sub New()

    End Sub

 

    Public Sub New(ByVal FirstName As StringByVal LastName As StringByVal AgeAs Integer)

        Me.FirstName = FirstName

        Me.LastName = LastName

        Me.Age = Age

    End Sub

 

    Public Function CompareTo(ByVal o As Person) As Integer

        If (Me.Age < o.Age) Then

            Return 1

        End If

        If (Me.Age > o.Age) Then

            Return -1

        End If

        Return 0

    End Function

 

 

    ' Properties

    Public Property Age As Integer

        Get

            Return Me._Age

        End Get

        Set(ByVal value As Integer)

            Me._Age = value

        End Set

    End Property

 

    Public Property FirstName As String

        Get

            Return Me._FirstName

        End Get

        Set(ByVal value As String)

            Me._FirstName = value

        End Set

    End Property

 

    Public Property LastName As String

        Get

            Return Me._LastName

        End Get

        Set(ByVal value As String)

            Me._LastName = value

        End Set

    End Property

 

 

    ' Fields

    Private _Age As Integer

    Private _FirstName As String

    Private _LastName As String

End Class

You can observe that the argument that overloads the CompareTo is a type of person rather than object now. With this manner the casting operation is avoided and the risk of receiving a compile or a run time errors are minimized. But let us be more practical as this example is demystifying the fact of profiting of the real IComparable interface services. I explain by giving a real example. The array type implements the IComparable interface in order to sort its objects collection and even the array list do the same thing to sort its objects collection internally. 

Say that I want to build my own objects container type. For this, I build a new type called Room witch plays the role of person objects container.

The class person will be presented as follow:

Public Class Person

    ' Methods

    Public Sub New()

    End Sub

 

    Public Sub New(ByVal FirstName As StringByVal LastName As StringByVal AgeAs Integer)

        Me.FirstName = FirstName

        Me.LastName = LastName

        Me.Age = Age

    End Sub

 

    ' Properties

    Public Property Age As Integer

        Get

            Return Me._Age

        End Get

        Set(ByVal value As Integer)

            Me._Age = value

        End Set

    End Property

 

    Public Property FirstName As String

        Get

            Return Me._FirstName

        End Get

        Set(ByVal value As String)

            Me._FirstName = value

        End Set

    End Property

 

    Public Property LastName As String

        Get

            Return Me._LastName

        End Get

        Set(ByVal value As String)

            Me._LastName = value

        End Set

    End Property

 

 

    ' Fields

    Private _Age As Integer

    Private _FirstName As String

    Private _LastName As String

End Class

 

The class Room witch plays the container role is designed as bellow:

Public Class Room

    ' Methods

    Public Sub AddNewPerson(ByVal o As Person)

        Me.oList.Add(o)

    End Sub

 

    Public Sub ReverseByAge()

        Me.oList.Reverse

    End Sub

 

    Public Sub SortByAge()

        Me.oList.Sort

    End Sub

 

 

    ' Properties

    Public ReadOnly Property Count As Integer

        Get

            Return Me.oList.Count

        End Get

    End Property

 

    Public Default Property Item(ByVal index As IntegerAs Person

        Get

            Return DirectCast(Me.oList.Item(index), Person)

        End Get

        Set(ByVal value As Person)

            Me.oList.Item(index) = value

        End Set

 End Property

 

When I try to run this program:

Class Program

    ' Methods

    Public Shared Sub Main(ByVal args As String())

        Dim i As Integer

        Console.WriteLine("Hello World!")

        Dim me As New Person("Bejaoui""Bechir", &H1D)

        Dim myFather As New Person("Bejaoui""Massinissa", &H41)

        Dim myGrandFather As New Person("Bejaoui""Shishaq", &H5F)

        Dim LivingRoom As New Room

        LivingRoom.AddNewPerson([me])

        LivingRoom.AddNewPerson(myFather)

        LivingRoom.AddNewPerson(myGrandFather)

        LivingRoom.SortByAge

        i

        For i = 0 To LivingRoom.Count - 1

            Console.WriteLine(("First name : " & LivingRoom.Item(i).FirstName & Environment.NewLine))

            Console.WriteLine(("Last name : " & LivingRoom.Item(i).LastName & Environment.NewLine))

            Console.WriteLine(("Age : " & LivingRoom.Item(i).Age & Environment.NewLine))

        Next i

        Console.WriteLine(("***  After reversing according to age ***" & Environment.NewLine))

        LivingRoom.ReverseByAge

        i

        For i = 0 To LivingRoom.Count - 1

            Console.WriteLine(("First name : " & LivingRoom.Item(i).FirstName & Environment.NewLine))

            Console.WriteLine(("Last name : " & LivingRoom.Item(i).LastName & Environment.NewLine))

            Console.WriteLine(("Age : " & LivingRoom.Item(i).Age & Environment.NewLine))

        Next i

        Console.WriteLine("Done")

        Console.Write("Press any key to continue . . . ")

        Console.ReadKey(True)

        Console.Beep

    End Sub

 

End Class

I receive a real time error that indicates that the sorting operation is failed and the cause here is that the person type doesn’t implement the IComparable interface. In order to render the sorting operation realizable, the IComparable interface has to be implemented first. Try now to implement the person type as follow:

 

Public Class Person

    Implements IComparable

    ' Methods

    Public Sub New()

    End Sub

 

    Public Sub New(ByVal FirstName As StringByVal LastName As StringByVal AgeAs Integer)

        Me.FirstName = FirstName

        Me.LastName = LastName

        Me.Age = Age

    End Sub

 

    Public Function CompareTo(ByVal o As ObjectAs Integer

        Dim Temp As Person

        Temp = CType(o, Person)

        If (Me.Age < o.Age) Then

            Return 1

        End If

        If (Me.Age > o.Age) Then

            Return -1

        End If

        Return 0

    End Function

 

 

    ' Properties

    Public Property Age As Integer

        Get

            Return Me._Age

        End Get

        Set(ByVal value As Integer)

            Me._Age = value

        End Set

    End Property

 

    Public Property FirstName As String

        Get

            Return Me._FirstName

        End Get

        Set(ByVal value As String)

            Me._FirstName = value

        End Set

    End Property

 

    Public Property LastName As String

        Get

            Return Me._LastName

        End Get

        Set(ByVal value As String)

            Me._LastName = value

        End Set

    End Property

 

 

    ' Fields

    Private _Age As Integer

    Private _FirstName As String

    Private _LastName As String

End Class   

 

Now, try to run the program and you will not receive this run time error again. Well, the fact is that this interface method enables the object to be compared to other instances of its own type.

IComparer interface

At the other hand, the IComparer interface is used to compare two objects issued from the same type and at the same time, consequently, it doesn’t be implemented within the type going to be compared. It is implemented within a separate type that has as a mission to compare a couple of objects. Let us turn back to our previous example and try to use the IComparer instead of the IComparable interface to sort objects within the room container.

Given this design of person type:

Public Class Person

    ' Methods

    Public Sub New()

    End Sub

 

    Public Sub New(ByVal FirstName As StringByVal LastName As StringByVal AgeAs Integer)

        Me.FirstName = FirstName

        Me.LastName = LastName

        Me.Age = Age

    End Sub

    ' Properties

    Public Property Age As Integer

        Get

            Return Me._Age

        End Get

        Set(ByVal value As Integer)

            Me._Age = value

        End Set

    End Property

 

    Public Property FirstName As String

        Get

            Return Me._FirstName

        End Get

        Set(ByVal value As String)

            Me._FirstName = value

        End Set

    End Property

 

    Public Property LastName As String

        Get

            Return Me._LastName

        End Get

        Set(ByVal value As String)

            Me._LastName = value

        End Set

    End Property

 

 

    ' Fields

    Private _Age As Integer

    Private _FirstName As String

    Private _LastName As String

End Class   

 

Say that we want to sort objects person by name now. First we ought to define a kind for comparer object that implements the IComparer interface:

Public Class CompareByName

    Implements IComparer

    ' Methods

    Public Function [Compare](ByVal object1 As ObjectByVal object2 As Object)As Integer

        Dim Temp1 As Person = DirectCast(object1, Person)

        Dim Temp2 As Person = DirectCast(object2, Person)

        Return String.Compare(Temp1.FirstName, Temp2.FirstName)

    End Function

 

End Class

Then we implement the Room container as follow:

Public Class Room

    ' Methods

    Public Sub AddNewPerson(ByVal o As Person)

        Me.oList.Add(o)

    End Sub

 

    Public Sub ReverseByAge()

        Me.oList.Reverse

    End Sub

 

    Public Sub SortByAge()

        Dim Comparer As New CompareByName

        Me.oList.Sort(Comparer)

    End Sub

 

    ' Properties

    Public ReadOnly Property Count As Integer

        Get

            Return Me.oList.Count

        End Get

    End Property

 

    Public Default Property Item(ByVal index As IntegerAs Person

        Get

            Return DirectCast(Me.oList.Item(index), Person)

        End Get

        Set(ByVal value As Person)

            Me.oList.Item(index) = value

        End Set

    End Property

End class

 

As you observe, I instantiate an CompareByName object witch serves as an argument to overload theoList.Sort method and that enables the Room container to compare the person objects collection twice by twice internally

 

Good Dotneting!!

COMMENT USING

Trending up