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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 12, 2025 (edit).