Is it the best override for Equals (in VB.NET) for an object having an unique ID?
Public Overrides Function Equals(ByVal obj As Object) As Boolean
If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
Return False
End If
Dim otherMyObject As MyObject = DirectCast(obj, MyObject)
Return Me.Id = otherMyObject.Id
End Function
I took that example from the MSDN, but not entirely sure if from all points of view (including performance) is the better solution.
EDIT:
How about comparing with this version:
Public Overrides Function Equals(ByVal obj As Object) As Boolean
Dim otherMyObject As MyObject = TryCast(obj, MyObject)
If otherMyObject Is Nothing Then
Return False
Else
Return Me.Id = otherMyObject.Id
End If
End Function
It depends what you mean by “an unique ID”. If you can guarantee that there won’t be any other objects in memory with the same ID, you can just inherit the functionality from
Object. If, however, you want to treat two objects of the same type and ID as being equal, then this looks fine. You’d want to overrideGetHashCodeas well though.You really need to consider what is going to use the equality implementation and what they’re expecting. If there can be two distinct objects with the same ID but different other properties, what does it mean for those to be “equal”? Is that appropriate or not?
It may make more sense to implement
IEqualityComparer(Of T)in something like an “IdEqualityComparer” type, for example. That’s a good way of expressing that an equality relation is useful but not necessarily a “natural, comprehensive” equality relation.