IComparable Interface defines a type-specific comparison method : IComparable « Data Structure « VB.Net






IComparable Interface defines a type-specific comparison method

 


Imports System.Collections

Public Class Temperature
    Implements IComparable
    Protected temperatureF As Double

    Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
        Implements IComparable.CompareTo

        Dim otherTemperature As Temperature = TryCast(obj, Temperature)
        If otherTemperature IsNot Nothing Then
            Return Me.temperatureF.CompareTo(otherTemperature.temperatureF)
        Else
           Throw New ArgumentException("Object is not a Temperature")
        End If   
    End Function

    Public Property Fahrenheit() As Double
        Get
            Return temperatureF
        End Get
        Set(ByVal Value As Double)
            Me.temperatureF = Value
        End Set
    End Property

    Public Property Celsius() As Double
        Get
            Return (temperatureF - 32) * (5/9)
        End Get
        Set(ByVal Value As Double)
            Me.temperatureF = (Value * 9/5) + 32
        End Set
    End Property
End Class

Public Module CompareTemperatures
   Public Sub Main()
      Dim temperatures As New ArrayList
      For ctr As Integer = 1 To 10
         Dim temp As New Temperature
         temp.Fahrenheit = ctr
         temperatures.Add(temp)   
      Next
      temperatures.Sort()
      For Each temp As Temperature In temperatures
         Console.WriteLine(temp.Fahrenheit)
      Next      
   End Sub
End Module

   
  








Related examples in the same category

1.Array Sort Object who implements the IComparableArray Sort Object who implements the IComparable
2.Binary SearchObject who implements the IComparableBinary SearchObject who implements the IComparable