Finding Property Differences Between Two C# Objects

Compare two objects and find the differences

One Flexible solution: You could use reflection to enumerate through all of the properties and determine which are and are not equal, then return some list of properties and both differing values.

Here's an example of some code that is a good start for what you are asking. It only looks at Field values right now, but you could add any number of other components for it to check through reflection. It's implemented using an extension method so all of your objects could use it.

TO USE

    SomeCustomClass a = new SomeCustomClass();
SomeCustomClass b = new SomeCustomClass();
a.x = 100;
List<Variance> rt = a.DetailedCompare(b);

My sample class to compare against

    class SomeCustomClass
{
public int x = 12;
public int y = 13;
}

AND THE MEAT AND POTATOES

using System.Collections.Generic;
using System.Reflection;

static class extentions
{
public static List<Variance> DetailedCompare<T>(this T val1, T val2)
{
List<Variance> variances = new List<Variance>();
FieldInfo[] fi = val1.GetType().GetFields();
foreach (FieldInfo f in fi)
{
Variance v = new Variance();
v.Prop = f.Name;
v.valA = f.GetValue(val1);
v.valB = f.GetValue(val2);
if (!Equals(v.valA, v.valB))
variances.Add(v);

}
return variances;
}

}
class Variance
{
public string Prop { get; set; }
public object valA { get; set; }
public object valB { get; set; }
}

Comparing object properties in c#

I was looking for a snippet of code that would do something similar to help with writing unit test. Here is what I ended up using.

public static bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class 
{
if (self != null && to != null)
{
Type type = typeof(T);
List<string> ignoreList = new List<string>(ignore);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (!ignoreList.Contains(pi.Name))
{
object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
object toValue = type.GetProperty(pi.Name).GetValue(to, null);

if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
{
return false;
}
}
}
return true;
}
return self == to;
}

EDIT:

Same code as above but uses LINQ and Extension methods :

public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore) where T : class
{
if (self != null && to != null)
{
var type = typeof(T);
var ignoreList = new List<string>(ignore);
var unequalProperties =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name) && pi.GetUnderlyingType().IsSimpleType() && pi.GetIndexParameters().Length == 0
let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
let toValue = type.GetProperty(pi.Name).GetValue(to, null)
where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
select selfValue;
return !unequalProperties.Any();
}
return self == to;
}

public static class TypeExtensions
{
/// <summary>
/// Determine whether a type is simple (String, Decimal, DateTime, etc)
/// or complex (i.e. custom class with public properties and methods).
/// </summary>
/// <see cref="http://stackoverflow.com/questions/2442534/how-to-test-if-type-is-primitive"/>
public static bool IsSimpleType(
this Type type)
{
return
type.IsValueType ||
type.IsPrimitive ||
new[]
{
typeof(String),
typeof(Decimal),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid)
}.Contains(type) ||
(Convert.GetTypeCode(type) != TypeCode.Object);
}

public static Type GetUnderlyingType(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Method:
return ((MethodInfo)member).ReturnType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
default:
throw new ArgumentException
(
"Input MemberInfo must be if type EventInfo, FieldInfo, MethodInfo, or PropertyInfo"
);
}
}
}

Compare two objects for properties with different values

I improved a little on Krishnas answer:

public List<string> GetChangedProperties<T>(object A, object B)
{
if (A != null && B != null)
{
var type = typeof(T);
var allProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var allSimpleProperties = allProperties.Where(pi => pi.PropertyType.IsSimpleType());
var unequalProperties =
from pi in allSimpleProperties
let AValue = type.GetProperty(pi.Name).GetValue(A, null)
let BValue = type.GetProperty(pi.Name).GetValue(B, null)
where AValue != BValue && (AValue == null || !AValue.Equals(BValue))
select pi.Name;
return unequalProperties.ToList();
}
else
{
throw new ArgumentNullException("You need to provide 2 non-null objects");
}
}

because it wasn't working for me. This one does and the only other thing you need to make it work is the IsSimpleType()-Extension Method that I adapted from this answer here (I only converted it into an extension method).

public static bool IsSimpleType(this Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// nullable type, check if the nested type is simple.
return type.GetGenericArguments()[0].IsSimpleType();
}
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
}

Finding property differences between two C# objects

IComparable is for ordering comparisons. Either use IEquatable instead, or just use the static System.Object.Equals method. The latter has the benefit of also working if the object is not a primitive type but still defines its own equality comparison by overriding Equals.

object originalValue = property.GetValue(originalObject, null);
object newValue = property.GetValue(changedObject, null);
if (!object.Equals(originalValue, newValue))
{
string originalText = (originalValue != null) ?
originalValue.ToString() : "[NULL]";
string newText = (newText != null) ?
newValue.ToString() : "[NULL]";
// etc.
}

This obviously isn't perfect, but if you're only doing it with classes that you control, then you can make sure it always works for your particular needs.

There are other methods to compare objects (such as checksums, serialization, etc.) but this is probably the most reliable if the classes don't consistently implement IPropertyChanged and you want to actually know the differences.


Update for new example code:

Address address1 = new Address();
address1.StateProvince = new StateProvince();

Address address2 = new Address();
address2.StateProvince = new StateProvince();

IList list = Utility.GenerateAuditLogMessages(address1, address2);

The reason that using object.Equals in your audit method results in a "hit" is because the instances are actually not equal!

Sure, the StateProvince may be empty in both cases, but address1 and address2 still have non-null values for the StateProvince property and each instance is different. Therefore, address1 and address2 have different properties.

Let's flip this around, take this code as an example:

Address address1 = new Address("35 Elm St");
address1.StateProvince = new StateProvince("TX");

Address address2 = new Address("35 Elm St");
address2.StateProvince = new StateProvince("AZ");

Should these be considered equal? Well, they will be, using your method, because StateProvince does not implement IComparable. That's the only reason why your method reported that the two objects were the same in the original case. Since the StateProvince class does not implement IComparable, the tracker just skips that property entirely. But these two addresses are clearly not equal!

This is why I originally suggested using object.Equals, because then you can override it in the StateProvince method to get better results:

public class StateProvince
{
public string Code { get; set; }

public override bool Equals(object obj)
{
if (obj == null)
return false;

StateProvince sp = obj as StateProvince;
if (object.ReferenceEquals(sp, null))
return false;

return (sp.Code == Code);
}

public bool Equals(StateProvince sp)
{
if (object.ReferenceEquals(sp, null))
return false;

return (sp.Code == Code);
}

public override int GetHashCode()
{
return Code.GetHashCode();
}

public override string ToString()
{
return string.Format("Code: [{0}]", Code);
}
}

Once you've done this, the object.Equals code will work perfectly. Instead of naïvely checking whether or not address1 and address2 literally have the same StateProvince reference, it will actually check for semantic equality.


The other way around this is to extend the tracking code to actually descend into sub-objects. In other words, for each property, check the Type.IsClass and optionally the Type.IsInterface property, and if true, then recursively invoke the change-tracking method on the property itself, prefixing any audit results returned recursively with the property name. So you'd end up with a change for StateProvinceCode.

I use the above approach sometimes too, but it's easier to just override Equals on the objects for which you want to compare semantic equality (i.e. audit) and provide an appropriate ToString override that makes it clear what changed. It doesn't scale for deep nesting but I think it's unusual to want to audit that way.

The last trick is to define your own interface, say IAuditable<T>, which takes a second instance of the same type as a parameter and actually returns a list (or enumerable) of all of the differences. It's similar to our overridden object.Equals method above but gives back more information. This is useful for when the object graph is really complicated and you know you can't rely on Reflection or Equals. You can combine this with the above approach; really all you have to do is substitute IComparable for your IAuditable and invoke the Audit method if it implements that interface.

Find difference between two objects in C#

You could use object.Equals(i,f) and omit the check for IEquatable. If it is neccessary but you would like to include nullables you could include them the following way:

        if (prop.PropertyType.IsGenericType)
{
if (prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
Type typeParameter = prop.PropertyType.GetGenericArguments()[0];

var i = prop.GetValue(initial);
var f = prop.GetValue(final);
if(object.Equals(i,f))
{
//...
}
}
}

So you check explicitly for Nullables.
The first line checks if the type is generic (true for Nullable List etc.) The second gets the underlying generic type (Nullable<>, List<>) and compares it with the Nullable<> type. The third line gets the first (and in case of Nullable<> only) parameter, just for the case you are interested in what type the Nullable is. So you will get int for Nullable. It is not needed in the code I written, but perhaps you are interested in it. Then the values of both properties are read and compared.

How to compare the same properties of two different class objects in C#?

I like a more controlled way better where you just type the compaire properties as you did in your sample, perhaps use an icomparable interface.

he reflection option that is offered and will be offered is slow, could give null pointer exceptions etc but write once work always, it's not a nuget package but here you go.

public static List<PropertyInfo> GetDifferences(object test1, object test2)
{
if (test1 is null)
throw new ArgumentNullException(nameof(test1));
if (test2 is null)
throw new ArgumentNullException(nameof(test2));

List<PropertyInfo> differences = new List<PropertyInfo>();
foreach (PropertyInfo property in test1.GetType().GetProperties())
{
if (test2.GetType().GetProperties().Any(a => a.Name.Equals(property.Name, StringComparison.Ordinal)))
{
object value1 = property.GetValue(test1, null);
object value2 = property.GetValue(test2, null);
if ((value1 == null) || !value1.Equals(value2))
{
differences.Add(property);
}
}
}
return differences;
}

It will return the properties that both have and are not the same.

Getting Difference Between Two Objects With Same Properties

Here is a very simple approach using reflection:

        var oOldRecord = new EmployeeMasterHistory();
oOldRecord.EmployeeNumber = 1;
var oNewRecord = new EmployeeMasterHistory();
oNewRecord.EmployeeNumber = 2;
oNewRecord.CompanyNumber = 3;

var oType = oOldRecord.GetType();

foreach (var oProperty in oType.GetProperties())
{
var oOldValue = oProperty.GetValue(oOldRecord, null);
var oNewValue = oProperty.GetValue(oNewRecord, null);
// this will handle the scenario where either value is null
if (!object.Equals(oOldValue, oNewValue))
{
// Handle the display values when the underlying value is null
var sOldValue = oOldValue == null ? "null" : oOldValue.ToString();
var sNewValue = oNewValue == null ? "null" : oNewValue.ToString();

System.Diagnostics.Debug.WriteLine("Property " + oProperty.Name + " was: " + sOldValue + "; is: " + sNewValue);
}
}

The output from this example is:

Property EmployeeNumber was: 1; is: 2
Property CompanyNumber was: null; is: 3

This probably needs cleanup, but should get you started down the right path.

How to compare properties between two objects

If you want to stick with comparison via reflection you should not use != (reference equality which will fail most of comparisons for boxed results of GetProperty calls) but instead use static Object.Equals method.

Sample how to use Equals method to compare two object in your reflection code.

 if (!Object.Equals(
item.GetValue(person, null),
dto.GetType().GetProperty(item.Name).GetValue(dto, null)))
{
diffProperties.Add(item);
}


Related Topics



Leave a reply



Submit