Reputation: 927
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.
Upvotes: 8
Views: 3214
Reputation: 7856
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.
Upvotes: 0
Reputation: 3940
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.
Upvotes: 0
Reputation: 8143
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.
Upvotes: 1
Reputation: 69280
Two ideas:
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.
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.
Upvotes: 4