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.
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.
We introduce a class
called Box. We specify that this class
Implements IComparable
and we specify Box as the generic type parameter.
Size
property is shown. It has public Get and Set parts. We use Size
to sort the Box objects.CompareTo
. Please notice its syntax—I added an underscore to break
the lines.CompareTo
, we simply use the Size
property of the Box object to return an Integer value.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
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
.
Sort
internally calls the CompareTo
method we implemented. It operates upon the IComparable
interface
.class
can be sorted through its IComparable
interface
. The Sort
method itself has no special knowledge of the Box.CompareTo
function.Some classes are rarely sorted. But for classes that are stored in groups (like in Lists), consider adding the IComparable
interface
.