PropertyInfo.GetValue unable to compare datetimes?

Total Post:108

 1664  View(s)
Rate this:

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;
  1. Post:412

    Re: PropertyInfo.GetValue unable to compare datetimes?

    Hi John, 

    You can us linq like this:

    return object1



          .All(x => object.Equals(x.GetValue(object1), x.GetValue(object2));



Enter your email address here always to be updated. We promise not to spam!