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?
C is not just what students use to learn programming. It's not an academic language. And I would say it's not the easiest language, because C is a rather low level programming language. Today, C is widely used in embedded devices, and it powers most of the Internet servers, which are built using Linux.
Possibly an off-the-wall suggestion but: consider not overriding Equals
in 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 an IEqualityComparer<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 whether Equals
will be further overridden.
Another approach to making the normal Equals
work 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 override Equals
and allow derived classes. sealed
FTW :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With