Cylindric Cylindric - 4 months ago 19
C# Question

Comparing two objects and returning the differences

I have to run comparisons between thousands of pairs of objects, and then perform actions depending on the differences.

Is there an "accepted" way of doing this?

class ObjectA
{
public string FieldA { get; set; }
public string FieldB { get; set; }
public string FieldC { get; set; }
}

class ObjectB
{
public string FieldA { get; set; }
public string FieldB { get; set; }
public string FieldC { get; set; }

public bool Equals(ObjectA obj)
{
if ((object)obj == null) return false;
if (this.FieldA != obj.FieldA) return false;
if (this.FieldB != obj.FieldB) return false;
if (this.FieldC != obj.FieldC) return false;
return true;
}
}

void test()
{
ObjectA a = new ObjectA();
ObjectB b = new ObjectB();
if (b.Equals(a))
{
Console.WriteLine("Same!!");
}
}


That does a fairly simple test to determine if
b=a
, but I also want to know what is different between them.

Should I add a
differences()
method that returns a list of properties? That seems a bit not.net though, as then I'll be bandying about strings.

public List<string> Differences(ObjectA obj)
{
List<string> differences = new List<string>();
if ((object)obj == null)
{
differences.Add("null");
}
else
{
if (this.FieldA != obj.FieldA) differences.Add("FieldA");
if (this.FieldB != obj.FieldB) differences.Add("FieldB");
if (this.FieldC != obj.FieldC) differences.Add("FieldC");
}
return differences;
}


Also that seems much slower than the first, as I would be creating all those
List<string>
, and not short-cutting the comparisons. Or is that just the price I pay for having the extra information?

Answer Source

There is nothing built in that will allow you to represent partial objects (i.e the differences).

Your approach seems reasonable for what you are trying to achieve.