views:

130

answers:

4

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.

+3  A: 

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.

Anders Abel
+2  A: 

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.

mathk
There are no two opinions about that this code needs refactoring, just don't have the time now to make it cleaner right now.And, alas, all attributes have to be equal.
vlood
A: 

If you're lucky, you'll identify one or two properties that are unique for the instance -- especially likely if you class represents a database entity -- and you will only have to compare those unique properties.

Dr Herbie
A: 

Use Regular Expression find and replace. It's a pain when you have to add fields *(removed ones get you a compile error), but you get the benefit of having compiled code.

Really, though, consider splitting the class up. If there's 100 fields, can they be grouped in component classes? 100 members is a lot of mess to have to manage.

David Kemp