Unexpected result when comparing values ​​obtained using PropertyInfo.GetValue ()

I have code that I use to scroll through the properties of certain objects and compare property values ​​that look something like this:

public static bool AreObjectPropertyValuesEqual(object a, object b) { if (a.GetType() != b.GetType()) throw new ArgumentException("The objects must be of the same type."); Type type = a.GetType(); foreach (PropertyInfo propInfo in type.GetProperties()) { if (propInfo.GetValue(a, null) != propInfo.GetValue(b, null)) { return false; } } return true; } 

Now for weird behavior. I created a class called PurchaseOrder with several properties, all of which are simple data types (strings, int, etc.). I create one instance in my Unit-Test module, and the other is my DataModel retrieving data from the database (MySql, I use MySqlConnector).

Although the debugger shows me that the property values ​​are identical, the comparison in the above code does not work.

That is: my Object A created in UnitTest has an Amount property value of 10. Object B obtained from my repository has an Amount property value of 10. Comparison failed! If I change the code to

 if (propInfo.GetValue(a, null).ToString() != propInfo.GetValue(b, null).ToString()) { ... } 

everything works as i expected. Comparison will also fail if I instantiate PurchaseOrder directly in UnitTest.

I would be very grateful for any user. Have a good day!

+4
source share
2 answers

PropertyInfo.GetValue returns an object, and your unit test does reference comparison ==. Try instead:

 if (!propInfo.GetValue(a, null).Equals(propInfo.GetValue(b, null))) 

You can replace null with something more reasonable ...

Alternatively you can try:

 if ((int?)propInfo.GetValue(a, null) != (int?)propInfo.GetValue(b, null)) 

(or any other simple type if it is not int ) that invokes type == type behavior.

+6
source

The reason for the rejection is that the equality test, which is applied above, is the reference equality test. Since the two objects returned by propInfo.GetValue(foo, null) , although equal to their own definitions, are separate objects, their references are different, and therefore the equality fails.

+1
source

All Articles