C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Size: The Size property is also shown. It has public Get and Set parts. We use Size to sort the Box objects.
CompareTo: 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).
VB.NET program that uses IComparable, CompareTo
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 Module
Output
80
90
100
110
And: Sort internally calls the CompareTo method we implemented. It operates upon the IComparable interface.
InterfaceThus: The Box class can be sorted through its IComparable interface. The Sort method itself has no special knowledge of the Box.