Last active
August 29, 2015 14:05
-
-
Save kstenson/c33aabadddd92d6123c1 to your computer and use it in GitHub Desktop.
A Naive Object diff extension method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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