开发者

Overriding Equals for an object with ID

开发者 https://www.devze.com 2023-04-12 12:41 出处:网络
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

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 exampl开发者_StackOverflow社区e 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 override GetHashCode as 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.


It depends on your requirements for "Equals" in your application. Does an instance ClassA with the same Id property always "Equal" another instance with the same Id? What if instance #1 has been changed, and some of the properties are different than instance #2, but still have the same Id. Are they still equal? In most definitions this would not be equal, but that's entirely up to your own requirements.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号