Does anyone have a template for writing a decent equals method – I remember in Effective Java there was problems around handling equals when dealing with subclasses.
I dont have the book with me and I cannot remember if it was practical advice – So how do you write a solid robust equals method implementation?
Possibly an off-the-wall suggestion but: consider not overriding
Equalsin the first place. Basically the nature of equality doesn’t work well with subclassing, as you mentioned. However, almost everywhere in the .NET API which uses equality (e.g. dictionaries, hash sets) allows anIEqualityComparer<T>to be passed in. Making a different object responsible for equality makes life much more flexible: you can use different objects to determine which criteria to use.Implementing
IEqualityComparer<T>is much simpler – you still need to check for nullity, but you don’t need to worry about whether the types are appropriate, or whetherEqualswill be further overridden.Another approach to making the normal
Equalswork more smoothly is to avoid inheritance entirely for the most part – I can’t remember the last time it really made sense in my code to overrideEqualsand allow derived classes.sealedFTW 🙂