views:

53

answers:

1

Hello!

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?

+3  A: 

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.

Oded
Thanks Oded.How do I avoid NullReferenceException on ContactName?תודה רבה
Shimmy
Check for `Me` being `Nothing` before trying to access anything on it.
Oded
Me cannot be nothing, I don't have to check it, the question is what about if the Id field equals Nothing, how should I get it's hashcode?
Shimmy
If it is Nothing, don't use it for generating the hash code.
Oded