Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

ObjectsComparer

> 编程语言
Open source

C# Framework provides mechanism to compare complex objects, allows to override comparison rules for specific properties and types.

362 stars0 likes1 views
WebsiteGitHub

About

C# Framework provides mechanism to compare complex objects, allows to override comparison rules for specific properties and types.

Objects Comparer

Introduction

It is quite common situation when complex objects should be compared. Sometimes objects can contain nested elements, or some members should be excluded from comparison (auto generated identifiers, create/update date etc.), or some members can have custom comparison rules (same data in different formats, like phone numbers). This small framework was developed to solve such kind of problems.

Briefly, Objects Comparer is an object-to-object comparer, which allows to compare objects recursively member by member and define custom comparison rules for certain properties, fields or types.

Objects comparer can be considered as ready to use framework or as a starting point for similar solutions.

Installation

Install-Package ObjectsComparer

Basic Examples

Let's suppose that we have 2 classes

csharp
public class ClassA
{
    public string StringProperty { get; set; }

    public int IntProperty { get; set; }

    public SubClassA SubClass { get; set; }
}

public class SubClassA
{
    public bool BoolProperty { get; set; }
}

There are some examples below how Objects Comparer can be used to compare instances of these classes.

csharp
//Initialize objects and comparer
var a1 = new ClassA { StringProperty = "String", IntProperty = 1 };
var a2 = new ClassA { StringProperty = "String", IntProperty = 1 };
var comparer = new Comparer();

//Compare objects
IEnumerable differences;
var isEqual = comparer.Compare(a1, a2, out differences);

//Print results
Debug.WriteLine(isEqual ? "Objects are equal" : string.Join(Environment.NewLine, differenses));

Objects are equal

In examples below Compare objects and Print results blocks will be skipped for brevity except some cases.

csharp
var a1 = new ClassA { StringProperty = "String", IntProperty = 1 };
var a2 = new ClassA { StringProperty = "String", IntProperty = 2 };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='IntProperty', Value1='1', Value2='2'.

csharp
var a1 = new ClassA { SubClass = new SubClassA { BoolProperty = true } };
var a2 = new ClassA { SubClass = new SubClassA { BoolProperty = false } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='SubClass.BoolProperty', Value1='True', Value2='False'.

csharp
var a1 = new StringBuilder("abc");
var a2 = new StringBuilder("abd");
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='', Value1='abc', Value2='abd'.

Enumerables (arrays)

csharp
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();

Objects are equal

csharp
var a1 = new[] { 1, 2 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Length', Value1='2', Value2='3'.

csharp
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 4, 3 };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='[1]', Value1='2', Value2='4'.

csharp
var a1 = new ArrayList { "Str1", "Str2" };
var a2 = new ArrayList { "Str1", 5 };
var comparer = new Comparer();

Difference: DifferenceType=TypeMismatch, MemberPath='[1]', Value1='Str2', Value2='5'.

Sets

csharp
var a1 = new[] { 1, 2, 3 };
var a2 = new[] { 1, 2, 3 };
var comparer = new Comparer();

Objects are equal

csharp
var a1 = new HashSet { 1, 2, 3 };
var a2 = new HashSet { 2, 1, 4 };
var comparer = new Comparer();

Difference: DifferenceType=MissedElementInSecondObject, MemberPath='', Value1='3', Value2=''. Difference: DifferenceType=MissedElementInFirstObject, MemberPath='', Value1='', Value2='4'.

Multidimensional arrays

csharp
var a1 = new[] { new[] { 1, 2 } };
var a2 = new[] { new[] { 1, 3 } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='[0][1]', Value1='2', Value2='3'.

csharp
var a1 = new[] { new[] { 1, 2 } };
var a2 = new[] { new[] { 2, 2 }, new[] { 3, 5 } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Length', Value1='1', Value2='2'.

csharp
var a1 = new[] { new[] { 1, 2 }, new[] { 3, 5 } };
var a2 = new[] { new[] { 1, 2 }, new[] { 3, 5, 6 } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='[1].Length', Value1='2', Value2='3'.

csharp
var a1 = new[,] { { 1, 2 }, { 1, 3 } };
var a2 = new[,] { { 1, 3, 4 }, { 1, 3, 8 } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Dimension1', Value1='2', Value2='3'.

csharp
var a1 = new[,] { { 1, 2 } };
var a2 = new[,] { { 1, 3 } };
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='[0,1]', Value1='2', Value2='3'.

Dynamic objects

C# supports several types of dynamic objects.

ExpandoObject

csharp
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 5;
a1.Field4 = 4;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
a2.Field4 = "C";
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.

Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field2', Value1='5', Value2=''.

Difference: DifferenceType=TypeMismatch, MemberPath='Field4', Value1='4', Value2='C'.

Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field3', Value1='', Value2='False'.

csharp
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 5;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.

Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field2', Value1='5', Value2=''.

Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field3', Value1='', Value2='False'.

Behavior if member not exists could be changed by providing custom ComparisonSettings (see Comparison Settings below).

csharp
dynamic a1 = new ExpandoObject();
a1.Field1 = "A";
a1.Field2 = 0;
dynamic a2 = new ExpandoObject();
a2.Field1 = "B";
a2.Field3 = false;
a2.Field4 = "S";
var comparer = new Comparer(new ComparisonSettings { UseDefaultIfMemberNotExist = true });

Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.

Difference: DifferenceType=ValueMismatch, MemberPath='Field4', Value1='', Value2='S'.

DynamicObject

Let’s assume that we have such implementation of the DynamicObject class. It is necessary to have a correct implementation of the method GetDynamicMemberNames, otherwise Objects Comparer wouldn't work in a right way.

…
csharp
dynamic a1 = new DynamicDictionary();
a1.Field1 = "A";
a1.Field3 = true;
dynamic a2 = new DynamicDictionary();
a2.Field1 = "B";
a2.Field2 = 8;
a2.Field3 = 1;
var comparer = new Comparer();

Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.

Difference: DifferenceType=TypeMismatch, MemberPath='Field3', Value1='True', Value2='1'.

Difference: DifferenceType=MissedMemberInFirstObject, MemberPath='Field2', Value1='', Value2='8'.

Compiler generated objects

csharp
dynamic a1 = new
{
    Field1 = "A",
    Field2 = 5,
    Field3 = true
};
dynamic a2 = new
{
    Field1 = "B",
    Field2 = 8
};
var comparer = new Comparer();

IEnumerable differences;
var isEqual = comparer.Compare((object)a1, (object)a2, out differences);

Difference: DifferenceType=ValueMismatch, MemberPath='Field1', Value1='A', Value2='B'.

Difference: DifferenceType=TypeMismatch, MemberPath='Field2', Value1='5', Value2='8'.

Difference: DifferenceType=MissedMemberInSecondObject, MemberPath='Field3', Value1='True', Value2=''.

This example requires some additional explanations. Types of the objects a1 and a2 were generated by compiler and are considered as the same type if and only if objects a1 and a2 have same set of members (same name and same type). If casting to (object) is skipped in case of different set of members RuntimeBinderException will be thrown.

Overriding Comparison Rules

To override comparison rule we need to create custom value comparer or provide function how to compare objects and how to convert these objects to string(optional) and filter function(optional). Value Comparer should be inherited from AbstractValueComparer or should implement IValueComparer.

csharp
public class MyValueComparer: AbstractValueComparer
{
    public override bool Compare(string obj1, string obj2, ComparisonSettings settings)
    {
        return obj1 == obj2; //Implement comparison logic here
    }
}

Override comparison rule for objects of particular type.

csharp
//Use MyComparer to compare all members of type string 
comparer.AddComparerOverride(new MyValueComparer());
comparer.AddComparerOverride(typeof(string), new MyValueComparer());
//Use MyComparer to compare all members of type string except members which name starts with "Xyz"
comparer.AddComparerOverride(typeof(string), new MyValueComparer(), member => !member.Name.StartsWith("Xyz"));
comparer.AddComparerOverride(new MyValueComparer(), member => !member.Name.StartsWith("Xyz"));

Override comparison rule for particular member (Field or Property).

…

Override comparison rule for particular member(s) (Field or Property) by name.

csharp
//Use MyValueComparer to compare all members with name equal to "StringProperty"
comparer.AddComparerOverride("StringProperty", new MyValueComparer());

Override comparison rule by member filter.

csharp
comparer.AddComparerOverride(new MyValueComparer(), m => m.Name == "StringProperty");

Overrides by type have highest priority, then overrides by member/member filter and overrides by member name have lowest priority. If more than one value comparers of the same type (by type/by name/by member name) could be applied to the same member, exception AmbiguousComparerOverrideResolutionException will be thrown during comparison.

Example:

csharp
var a1 = new ClassA();
var a2 = new ClassA();
comparer.AddComparerOverride(valueComparer1, member => member.Name.StartsWith("String"));
comparer.AddComparerOverride(valueComparer2, member => member.Name.EndsWith("Property"));

var result = comparer.Compare(a1, a2);//Exception here

Ignoring members

Ignores members of particular type.

csharp
comparer.IgnoreMember();

Ignores particular member.

csharp
comparer.IgnoreMember(() => new A().TestProperty1);

Ignores by member filter.

csharp
comparer.IgnoreMember(member => member.Name == "TestProperty1");

Ignores particular member by name.

csharp
comparer.IgnoreMember("TestProperty1");

Comparison Settings

Comparer constructor has an optional settings parameter to configure some aspects of comparison.

RecursiveComparison

True by default. If true, all members which are not primitive types, do not have custom comparison rule and do not implement ICompareble will be compared using the same rules as root objects.

EmptyAndNullEnumerablesEqual

False by default. If true, empty enumerables (arrays, collections, lists etc.) and null values will be considered as equal values.

UseDefaultIfMemberNotExist

If true and member does not exist, objects comparer will consider that this member is equal to default value of opposite member type. Applicable for dynamic types comparison only. False by default.

Comparison Settings class allows to store custom values that can be used in custom comparers.

csharp
SetCustomSetting(T value, string key = null)
GetCustomSetting(string key = null)

Factory

Factory provides a way to encapsulate comparers creation and configuration. Factory should implement IComparersFactory or should be inherited from ComparersFactory.

csharp
public class MyComparersFactory: ComparersFa

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#comparing-objectscomparisoncsharpdotnet

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言