Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing A Good C# Equals Method

Tags:

c#

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?

like image 335
Jack Kada Avatar asked Mar 24 '10 17:03

Jack Kada


People also ask

Is C easy for beginners?

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.


1 Answers

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 :)

like image 87
Jon Skeet Avatar answered Oct 01 '22 19:10

Jon Skeet