Skip to content

Instantly share code, notes, and snippets.

@ChrisMissal
Created September 24, 2012 22:52
Show Gist options
  • Save ChrisMissal/3778939 to your computer and use it in GitHub Desktop.
Save ChrisMissal/3778939 to your computer and use it in GitHub Desktop.
Creates a dynamic object from the differences of two strongly typed objects.
public static class Diff
{
public static dynamic GetDynamicDiff<T>(T left, T right)
{
return GetDynamicDiff(left, right, typeof(T));
}
private static dynamic GetDynamicDiff<T>(T left, T right, Type type)
{
dynamic expando = new System.Dynamic.ExpandoObject();
var properties = type.GetProperties();
foreach (var leftProperty in properties)
{
var rightProperty = type.GetProperty(leftProperty.Name);
var leftValue = leftProperty.GetValue(left, null);
var rightValue = rightProperty.GetValue(right, null);
if (leftProperty.PropertyType.IsValueType && !object.Equals(leftValue, rightValue))
{
((IDictionary<string, object>)expando).Add(leftProperty.Name, rightValue);
}
else if (!leftProperty.PropertyType.IsValueType && !(leftValue is string))
{
var diff = GetDynamicDiff(leftValue, rightValue, leftProperty.PropertyType);
if (!((IDictionary<string, object>)diff).Any())
continue;
((IDictionary<string, object>)expando).Add(leftProperty.Name, ((IDictionary<string, object>)diff).Any() ? diff : null);
}
else if (!object.Equals(leftValue, rightValue))
{
((IDictionary<string, object>)expando).Add(leftProperty.Name, rightValue);
}
}
return expando;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment