Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Equals for classes with many properties in C#

Tags:

c#

equals

I have a number of data classes that have over 25 properties of different value types (and this may change in the future as requirements change). I would like to override equals, mostly for unit testing purposes.

Currently, the only way I know how to do this is to actually test for equality of each property hard coded. This seems bad for two reasons - first, I will have to write a lot of code to test 25 properties for equality - second, if a property in one of the classes is added at a later point in time, the Equals method will not check that, and most likely this will go unnoticed and lead to problems down the road.

Since Equals usually checks for the properties of classes, there should be a way to dynamically compare the properties of the classes being compared, which ensures that property changes to a class don't result in an incorrect implementation of Equals. Is there a way to do this?

like image 652
Ben B. Avatar asked Aug 30 '11 14:08

Ben B.


People also ask

Can == be overridden?

Terminology note: == is never overridden. It's overloaded.

Why should you override Equals method in C#?

For a value type, you should always override Equals, because tests for equality that rely on reflection offer poor performance. You can also override the default implementation of Equals for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality.

How do you override a property?

An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property. Beginning with C# 9.0, read-only overriding properties support covariant return types. The overridden property must be virtual , abstract , or override .

Which of the following are required to override the Equals () method in C#?

ValueType. This type overrides the Equals method because equality of value types is based on whether the two objects you're comparing contain the same data.


2 Answers

you could write something like this using reflection - but this would be very slow. I would stick with overriding equals but think about which part you really need for equal. I usually only check the immutable parts (like Id) for equality and just ignore the mutable fields and I think this is a good practice.

like image 53
Random Dev Avatar answered Oct 29 '22 04:10

Random Dev


Try using reflection to compare the properties. See Comparing object properties in c# for more info!

like image 45
rickythefox Avatar answered Oct 29 '22 05:10

rickythefox