Skip to content

Custom Comparers

Greg Finzer edited this page Apr 28, 2019 · 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(CompareParms parms)
	{
		var st1 = (SpecificTenant)parms.Object1;
		var st2 = (SpecificTenant)parms.Object2;

		if (st1.Name != st2.Name || st1.Amount > 100 || st2.Amount < 100)
		{
			AddDifference(parms);
		}
	}
}

Usage

CompareLogic compareLogic = new CompareLogic();

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

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

//No Custom Comparer
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