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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…