Should an override of Equals on a reference type always mean value equality?

后端 未结 3 1979
情话喂你
情话喂你 2020-12-10 14:31

Without doing anything special for a reference type, Equals() would mean reference equality (i.e. same object). If I choose to override Equals() f

3条回答
  •  执念已碎
    2020-12-10 14:53

    Yes, deciding the right rules for this is tricky. There is no single "right" answer here, and it will depend a lot on both context and preference Personally, I rarely bother thinking about it much, just defaulting to reference equality on most regular POCO classes:

    • the number of cases when you use something like Person as a dictionary-key / in a hash-set is minimal
      • and when you do, you can provide a custom comparer that follows the actual rules you want it to follow
      • but most of the time, I'd use simply the int Id as the key in a dictionary (etc) anyway
    • using reference equality means that x==y gives the same result whether x/y are Person or object, or indeed T in a generic method
    • as long as Equals and GetHashCode are compatible, most things will just about work out, and one easy way to do that is to not override them

    Note, however, that I would always advise the opposite for value-types, i.e. explicitly override Equals / GetHashCode; but then, writing a struct is really uncommon

提交回复
热议问题