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!
source share