Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two object from the same class with tons of fields

I got two objects from the same class and I need to compare them field by field. The problem is that they have close to hundred fields and it would be helluva work to write that by hand.

Do you know any way to do that the easier way? Reflections in Java could be a solution, but yet it seems to me like a hack. And I seek a C# solution after all.

like image 891
vlood Avatar asked Jul 13 '10 08:07

vlood


2 Answers

Two ideas:

  1. Use reflection (it is available in C#) runtime and loop over the fields of the clas comparing them. If you want to be able to exclude certain fields you could do that by creating an attribute class and mark the fields you don't want to compare with that attribute.

  2. Use reflection to loop over the fields in the same way and generate the required comparison code. This way you will have "real" code but won't have to write and maintain it yourself. Attributes can be used to fine-tune the comparison code generated.

like image 188
Anders Abel Avatar answered Nov 16 '22 12:11

Anders Abel


The best is to refactor your code, hundred fields is way to mush.

If you can't because is a legacy code find out which attribute make them equals.

like image 24
mathk Avatar answered Nov 16 '22 12:11

mathk