0

I am looping through two objects to see if all items within the two objects are the same. After adding a watch at the point where it is return false, I see the same values. The two items being compared are both datetime. They have the exact same value, but are returning false. My question is Considering these two items are both datetime, are they causing the issue? If not, is there a better way to compare my two objects?

private bool CompareObj(Visit object1, Visit object2)
{
    foreach (var obj1PropertyInfo in object1.GetType().GetProperties())
    {
        foreach (var obj2PropertyInfo in object2.GetType().GetProperties())
        {
            if (obj1PropertyInfo.Name == obj2PropertyInfo.Name && obj1PropertyInfo.GetValue(object1, null) != obj2PropertyInfo.GetValue(object2, null))
            {
                return false;
            }
        }
    }
    return true;
}
dee-see
  • 23,668
  • 5
  • 58
  • 91
CBC_NS
  • 1,961
  • 4
  • 27
  • 47

3 Answers3

2

Here is a linq way:

return object1
      .GetType()
      .GetProperties()
      .All(x => object.Equals(x.GetValue(object1), x.GetValue(object2));
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Use Equals (works for nulls as well)

private bool CompareObj(Visit object1, Visit object2)
{
    foreach (var obj1PropertyInfo in object1.GetType().GetProperties())
    {
        foreach (var obj2PropertyInfo in object2.GetType().GetProperties())
        {
            if (obj1PropertyInfo.Name == obj2PropertyInfo.Name
            && !Equals(obj1PropertyInfo.GetValue(object1, null),
            obj2PropertyInfo.GetValue(object2, null)))
            {
                return false;
            }
        }
    }
    return true;
}
firda
  • 3,268
  • 17
  • 30
0

Credit to Michael Lieu for suggesting this first, but I will put it in answer form since he did not.

If you are only interested in object equality (and not whether or not the objects share the same reference), use the .Equals method. By default (i.e., assuming that it is not overloaded), == compares references, which (presumably) are the same in your case because these are 2 different instances of DateTime.

This is all under the assumption that you are comparing 2 DateTime instances, of course: private bool CompareObj(Visit object1, Visit object2) { return object.Equals(object1, object2); }

If you are comparing more complex objects, you may need the loop with reflection to iterate through the properties.

Summary: If you are only interested in equality, but you don't care whether or not the references are identical, use Equals instead of ==.

Douglas Barbin
  • 3,595
  • 2
  • 14
  • 34