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?
Asked
Active
Viewed 3,373 times
4

Philip Pittle
- 11,821
- 8
- 59
- 123

Coding man
- 957
- 1
- 18
- 44
-
Pretty sure this isn't possible without knowing the names of the fields. I may be wrong though – JKennedy Aug 01 '14 at 09:47
-
1It 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 Answers
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).
-
An exercise for "Coding man" may be to handle complex property types such as generic lists. – Rob Epstein Aug 01 '14 at 09:55
-
-
question said class only contains fields and not properties. Confused why your answer got accepted – Felix Keil Aug 01 '14 at 10:59
-4
Try this assert:
CollectionAssert.AreEqual(Obj1, Obj2);

Thanos Markou
- 2,587
- 3
- 25
- 32
-
1
-
This will use the built in .net Equal methods which will do a referential equality check. – Philip Pittle Aug 01 '14 at 12:19