IComparable. How can we compare 2 objects? With the IComparable interface, we implement CompareTo and return an Integer. This indicates which object comes before the other.
Implements keyword. In VB.NET, we must use the implements keyword to specify that we want to use this interface. Then we must add a CompareTo function.
Detail Next we implement CompareTo. Please notice its syntax. I added an underscore to break the lines.
And In CompareTo, we simply use the Size property of the Box object to return an Integer value.
Result The value one means more than (after). The number zero means equal. And minus one means less than (before).
Class Box
Implements IComparable(Of Box)
Public Sub New(ByVal size As Integer)
sizeValue = size
End Sub
Private sizeValue As Integer
Public Property Size() As Integer
Get
Return sizeValue
End Get
Set(ByVal value As Integer)
sizeValue = value
End Set
End Property
Public Function CompareTo(other As Box) As Integer _
Implements IComparable(Of Box).CompareTo
' Compare sizes.
Return Me.Size().CompareTo(other.Size())
End Function
End Class
Module Module1
Sub Main()
' Create list of Box objects.
Dim boxes As List(Of Box) = New List(Of Box)
boxes.Add(New Box(100))
boxes.Add(New Box(90))
boxes.Add(New Box(110))
boxes.Add(New Box(80))
' Sort with IComparable implementation.
boxes.Sort()
For Each element As Box In boxes
Console.WriteLine(element.Size())
Next
End Sub
End Module80
90
100
110
Code info. In Main, we create a List with 4 Box objects in it. We use New to specify the sizes of the boxes in the creation expression. We then invoke the Sort Sub.
And Sort internally calls the CompareTo method we implemented. It operates upon the IComparable interface.
Thus The Box class can be sorted through its IComparable interface. The Sort method itself has no special knowledge of the Box.
Result In the results, our Box objects are sorted by size, from lowest to highest. This is called an ascending sort.
Tip For a descending sort, try reversing the order you compare variables in the CompareTo function.
Summary. Some classes are rarely sorted. But for classes that are stored in groups (like in Lists), consider adding the IComparable interface.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 9, 2022 (edit link).