Skip to content

Instantly share code, notes, and snippets.

@kstenson
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kstenson/c33aabadddd92d6123c1 to your computer and use it in GitHub Desktop.
Save kstenson/c33aabadddd92d6123c1 to your computer and use it in GitHub Desktop.
A Naive Object diff extension method
public static class ObjectExtensions
{
public static IEnumerable<Change> Diff<T>(this T obj1, T obj2)
{
PropertyInfo[] properties = typeof(T).GetProperties();
List<Change> changes = new List<Change>();
foreach (PropertyInfo pi in properties)
{
object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);
if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
{
changes.Add(new Change(){Name = pi.Name, Previous = value1, New = value2});
}
}
return changes;
}
public static IEnumerable<Change> DeepDiff(this object obj1, object obj2)
{
var type = obj1.GetType();
PropertyInfo[] properties = type.GetProperties();
List<Change> changes = new List<Change>();
foreach (PropertyInfo pi in properties)
{
object value1 = type.GetProperty(pi.Name).GetValue(obj1, null);
object value2 = type.GetProperty(pi.Name).GetValue(obj2, null);
if (value1.GetType() != value2.GetType())
{
changes.Add(new Change() { Name = pi.Name, Previous = value1, New = value2 });
continue;
}
if (pi.PropertyType != typeof(string) && !value1.GetType().IsValueType && !value2.GetType().IsValueType)
{
var changeset = value1.DeepDiff(value2);
changes.AddRange(changeset);
continue;
}
if (value1 != value2 && (value1 == null || !value1.Equals(value2)))
{
changes.Add(new Change() { Name = pi.Name, Previous = value1, New = value2 });
}
}
return changes;
}
}
public class Change
{
public string Name { get; set; }
public object Previous { get; set; }
public object New { get; set; }
public override string ToString()
{
return string.Format("Property {0} changed from {1} to {2}", Name, Previous, @New);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment