Skip to content

Custom Comparers

GregFinzer edited this page Nov 21, 2017 · 7 revisions

To add a custom comparer, implement BaseTypeComparer and add to the Config.CustomComparers collection. Custom comparers are run before the built in comparers.

Example

public class MyCustomComparer : BaseTypeComparer { public MyCustomComparer(RootComparer rootComparer) : base(rootComparer) { }

public override bool IsTypeMatch(Type type1, Type type2) { return type1 == typeof (SpecificTenant); }

public override void CompareType(ComparisonResult result, object object1, object object2, string breadCrumb) { var st1 = (SpecificTenant)object1; var st2 = (SpecificTenant)object2;

if (st1.Name != st2.Name || st1.Amount > 100 || st2.Amount < 100) { Difference difference = new Difference { PropertyName = breadCrumb, Object1Value = object1.ToString(), Object2Value = object2.ToString() };

result.Differences.Add(difference); } } }

Usage

SpecificTenant tenant1 = new SpecificTenant(); tenant1.Name = "wire"; tenant1.Amount = 37;

SpecificTenant tenant2 = new SpecificTenant(); tenant2.Name = "wire"; tenant2.Amount = 155;

//No Custom Comparer CompareLogic compareLogic = new CompareLogic(); Assert.IsFalse(compareLogic.Compare(tenant1, tenant2).AreEqual);

//specify custom selector compareLogic.Config.CustomComparers.Add(new MyCustomComparer(RootComparerFactory.GetRootComparer()));

Assert.IsTrue(compareLogic.Compare(tenant1, tenant2).AreEqual);

tenant2.Amount = 42; Assert.IsFalse(compareLogic.Compare(tenant1, tenant2).AreEqual);

Clone this wiki locally