Add Distinction to Your Code: VB: Implement a Comparer Class: Listing 1

A comparer class must implement IEquatable(Of T) and override the System.Object's or the base class' Equals(object) method and GetHashCode method. The GetHashCode method must return the same value for objects to be considered equal because it's the first method called in the equality test.

Class Location
    Implements IEquatable(Of Location)

    Public Property State() As String
    Public Property Suburb() As String
    Public Property PostCode() As Int32

    Public Overrides Function GetHashCode() As Int32
        Return PostCode.GetHashCode Xor _
            State.GetHashCode Xor _
    End Function

    Public Overrides Function Equals( _
        ByVal obj As Object) As Boolean
        Return Equals(TryCast(obj, Location))
    End Function

    Public Overloads Function Equals( _
        ByVal other As Location) As Boolean _
        Implements IEquatable(Of Location).Equals
        If other Is Nothing Then Return False
        Return PostCode = other.PostCode _
            AndAlso State.Equals(other.State, _
            StringComparison.CurrentCultureIgnoreCase) _
            AndAlso Suburb.Equals(other.Suburb, _
    End Function

End Class
comments powered by Disqus

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events