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
  • 10,880
  • 7
  • 52
  • 113
Coding man
  • 947
  • 1
  • 17
  • 42
  • Pretty sure this isn't possible without knowing the names of the fields. I may be wrong though – User1 Aug 01 '14 at 09:47
  • 1
    It is possible. Writing answer now (clue, it involves reflection). –  Aug 01 '14 at 09:47
  • http://www.csharp-examples.net/reflection-examples/ – L.B Aug 01 '14 at 09:47
  • Yes, using lots and lots of reflection – Philip Pittle Aug 01 '14 at 09:48
  • possible duplicate of [Comparing two objects by iterating recursively through all the properties' properties?](http://stackoverflow.com/questions/25062428/comparing-two-objects-by-iterating-recursively-through-all-the-properties-prope) – Adriano Repetti Aug 01 '14 at 09:50
  • Using Reflection or BinaryFormatter to compare serialized raw byte[] arrays. – Adriano Repetti Aug 01 '14 at 09:51
  • possible duplicate of [Compare the content of two objects for equality](http://stackoverflow.com/questions/375996/compare-the-content-of-two-objects-for-equality) – frank koch Aug 01 '14 at 10:03

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,537
  • 3
  • 23
  • 32