I'm trying to compare objects within two different Dictionary<string,object>
(to find differences in a versioned repository.
The dictionary can contains any serialize type, either value-type or reference-type.
I loop on all keys to perform the comparison. Because of the value type boxing, I implemented a small utility method found on SO :
private static bool AreValueEquals(object o1, object o2)
{
return (o1 != null && o1.GetType().IsValueType)
? o1.Equals(o2)
: o1 == o2;
}
This method is used in my main method like this:
private static List<string> GetDifferent(Dictionary<string, object> currentValues, Dictionary<string, object> previousValues)
{
var changed = from fieldName in currentValues.Keys.Union(previousValues.Keys).Distinct()
let currentVal = GetIfExists(currentValues, fieldName)
let previousVal = GetIfExists(previousValues, fieldName)
where !AreValueEquals(currentVal, previousVal)
select fieldName;
return changed.ToList();
}
private static object GetIfExists(Dictionary<string, object> values, string fieldName)
{
return values.ContainsKey(fieldName) ? values[fieldName] : null;
}
While the AreValueEquals
method works as expected on my test case (dotnetfiddle), at runtime, I get unexpected result:
I don't understand this result. Is my implementation correct? How to fix?