Search code examples
vb.netgenericsiequatable

Cascading IEquatable(Of T)


I have several entities I need to make IEquatable(Of TEntity) respectively.

I want them first to check equality between EntityId, then if both are zero, should check regarding to other properties, for example same contact names, same phone number etc.

How is this done?


Solution

  • Adapted from MSDN IEquatable:

    Public Class Entity : Implements IEquatable(Of Entity)
    
        Public Overloads Function Equals(other As Entity) As Boolean _
                        Implements IEquatable(Of Entity).Equals
           If Me.Id = other.Id Then
               Return Me.ContactName = other.ContactName AndAlso Me.PhoneNumber = other.PhoneNumber
           Else
              Return False
           End If
        End Function
    
        Public Overrides Function Equals(obj As Object) As Boolean
           If obj Is Nothing Then Return MyBase.Equals(obj)
    
           If TypeOf obj Is Entity
              Return Equals(DirectCast(obj, Entity)) 
           Else
              Return False  
           End If
        End Function   
    
        Public Overrides Function GetHashCode() As Integer
           Return Me.Id.GetHashCode() Xor Me.ContactName.GetHashCode() Xor Me.PhoneNumber.GetHashCode()
        End Function
    
        Public Shared Operator = (entity1 As Entity, entity2 As Entity) As Boolean
           Return entity1.Equals(entity2)
        End Operator
    
       Public Shared Operator <> (entity1 As Entity, entity2 As Entity) As Boolean
          Return Not entity1.Equals(entity2)
       End Operator
    
    
    End Class
    

    Note:

    The implementations of GetHashCode is naive and if you need to use this in a production environment, read the answers to this SO question.