PropertiesComparer
Comparator for two instances of the same type, comparing each property.
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Constraints.Comparers
{
[NullableContext(1)]
[Nullable(0)]
internal static class PropertiesComparer
{
public static EqualMethodResult Equal(object x, object y, ref Tolerance tolerance, ComparisonState state, NUnitEqualityComparer equalityComparer)
{
Type type = x.GetType();
Type type2 = y.GetType();
if (type != type2)
return EqualMethodResult.TypesNotSupported;
if (type.IsPrimitive)
return EqualMethodResult.TypesNotSupported;
PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
if (properties.Length == 0 || properties.Any((PropertyInfo p) => p.GetIndexParameters().Length != 0))
return EqualMethodResult.TypesNotSupported;
ComparisonState state2 = state.PushComparison(x, y);
string name = type.Name;
BitArray bitArray = new BitArray(properties.Length);
int num = 0;
for (int i = 0; i < properties.Length; i++) {
PropertyInfo propertyInfo = properties[i];
object value = propertyInfo.GetValue(x, null);
object value2 = propertyInfo.GetValue(y, null);
switch (equalityComparer.AreEqual(value, value2, ref tolerance, state2)) {
case EqualMethodResult.ComparedNotEqual:
return PropertyNotEqualResult(equalityComparer, i, name, propertyInfo.Name, value, value2);
case EqualMethodResult.ToleranceNotSupported:
bitArray.Set(i, true);
num++;
break;
}
}
if (num == properties.Length)
return EqualMethodResult.ToleranceNotSupported;
if (num != 0) {
Tolerance tolerance2 = Tolerance.Exact;
for (int j = 0; j < properties.Length; j++) {
if (bitArray.Get(j)) {
PropertyInfo propertyInfo2 = properties[j];
object value3 = propertyInfo2.GetValue(x, null);
object value4 = propertyInfo2.GetValue(y, null);
EqualMethodResult equalMethodResult = equalityComparer.AreEqual(value3, value4, ref tolerance2, state2);
if (equalMethodResult == EqualMethodResult.ComparedNotEqual)
return PropertyNotEqualResult(equalityComparer, j, name, propertyInfo2.Name, value3, value4);
}
}
}
return EqualMethodResult.ComparedEqual;
}
private static EqualMethodResult PropertyNotEqualResult(NUnitEqualityComparer equalityComparer, int i, string declaringTypeName, string propertyName, [Nullable(2)] object xPropertyValue, [Nullable(2)] object yPropertyValue)
{
NUnitEqualityComparer.FailurePoint item = new NUnitEqualityComparer.FailurePoint {
Position = i,
PropertyName = declaringTypeName + "." + propertyName,
ExpectedHasData = true,
ExpectedValue = xPropertyValue,
ActualHasData = true,
ActualValue = yPropertyValue
};
equalityComparer.FailurePoints.Insert(0, item);
return EqualMethodResult.ComparedNotEqual;
}
}
}