I have a function of an class in C# that compares one object to another. More or less a Equals function but with some added code. My object has quite a few variables and I would like to compare each and if any are different add them to a data table. Right now my function looks something like:
public bool compareSysInfo(SystemInfo expected, SystemInfo comp)
{
ComparePopup popup = new ComparePopup();
bool finalResult = true;//initial assumption that they are equal
//compares branding
if (expected.branding != comp.branding)
{
finalResult = false;
popup.addDataToTable("Branding", comp.getBranding() + "", expected.getBranding() + "");
}
//compares pro #
if (expected.getPro() != comp.getPro())
{
finalResult = false;
popup.addDataToTable("Pro Number", comp.getPro() + "", expected.getPro() + "");
}
It continues like that for all the variables. I would like to avoid excessive if statements, is there a way to create a abstract method and use a loop? I looked into delegates but I’m not sure how to use them in this context. Maybe I’m going about this wrong and should do something completely different like adding them to a collections and just using a for loop to compare the objects. I feel like I’m missing something obvious. I know any place that has repetitive code like this you can implement better, it’s just I don’t know how. Any advice here would be great.
Thanks for the help.
Create a strategy class, inherit from it for each rule, and provide your class with a list containing these:
Then for each rule check you implement an instance of the Rule class (or interface):
This strategy affords you the ability to add, remove, or modify rules and what they do independently of the code that needs to use them.