8

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

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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.
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.