4

Assuming that Obj1 and Obj2 are objects of the same class and the class contains only fields, is it possible to check whether the two objects have the same data if the fields of the class are not known?

Philip Pittle
  • 11,821
  • 8
  • 59
  • 123
Coding man
  • 957
  • 1
  • 18
  • 44

2 Answers2

7
var haveSameData = false;

foreach(PropertyInfo prop in Obj1.GetType().GetProperties())
{
    haveSameData = prop.GetValue(Obj1, null).Equals(prop.GetValue(Obj2, null));

    if(!haveSameData)
       break;
}

This is based on assumptions (objects are of the same type), and could probably be refactored so that it's more defensive, but I'm keeping it readable so you can grasp what I'm trying to do.

In a nutshell, use reflection to iterate over the fields and check the values of each until satisfied that they don't match (no need to keep iterating after this).

-4

Try this assert:

CollectionAssert.AreEqual(Obj1, Obj2);
Thanos Markou
  • 2,587
  • 3
  • 25
  • 32