Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
You need to provide a mechanism that allows two custom objects to be compared.
Determine what data you want to use for the basis of your comparison, and implement the IComparable interface.
The IComparable interface defines a single CompareTo method that accepts an object for comparison and returns an integer. The integer can take one of the following three values:
Zero, which means the objects are equal.
Less than zero (typically - 1), which means that the current object is less than the object that was supplied as a parameter.
Greater than zero (typically 1), which means that the current object is greater than the object that was supplied as a parameter.
You can evaluate the object contents on your own and decide which value to return. However, you can often use the CompareTo method of one of the contained data types to make the comparison. For example, in the code that follows, the Person object performs an alphabetical comparison (based on the last name, then the first name) on two Person instances using the String.CompareTo implementation.
Public Class Person
Implements IComparable
Private _FirstName As String
Private _LastName As String
' (Property procedure and constructor code omitted.)
Public Function CompareTo(ByVal obj As Object) As Integer _
Implements System.IComparable.CompareTo
If Not TypeOf obj Is Person Then
Throw New ArgumentException("Object is not a Person")
End If
Dim Compare As Person = CType(obj, Person)
' Compare last names
Dim result As Integer = Me.LastName.CompareTo(Compare.LastName)
' If last names are equal, compare first names
If result = 0 Then
result = Me.FirstName.CompareTo(Compare.FirstName)
End If
Return result
End Function
End ClassHere’s a simple test of a comparable object:
Dim PersonA As New Person("Andrew", "Sempf")
Dim PersonB As New Person("Andrew", "Sempf")
If PersonA Is PersonB Then
' This never happens.
Console.WriteLine("These Person objects point to the same data " & _
"in memory.")
End If
If PersonA.CompareTo(PersonB) = 0 Then
' This always happens.
Console.WriteLine("These Person objects represent the same person.")
End IfOnce you implement CompareTo, you can sort arrays or ArrayList objects that contain your object, as described in recipe 3.8. If you need to create an
object that can be sorted in several different ways, you will need to create separate IComparer instances, as described in recipe 3.9.
Note
Implementing IComparable does not give you the ability to use the greater than (>) and less than (<) operators to compare your objects because Visual Basic .NET does not support operator overloading. Instead, you must call CompareTo explicitly.