Last active
November 3, 2020 14:54
-
-
Save MiroslavMikus/8d8ebb9b89d033ff996dc0908f13b19e to your computer and use it in GitHub Desktop.
Generic object comparsion based on reflection.
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
public class ReflectionCompare | |
{ | |
protected List<PropertyInfo> SimpleReflectionCompare<T>(T first, T second) | |
where T : class | |
{ | |
List<PropertyInfo> differences = new List<PropertyInfo>(); | |
foreach (PropertyInfo property in first.GetType().GetProperties()) | |
{ | |
object value1 = property.GetValue(first, null); | |
object value2 = property.GetValue(second, null); | |
if (!value1.Equals(value2)) | |
{ | |
differences.Add(property); | |
} | |
} | |
return differences; | |
} | |
protected List<KeyValuePair<Type, PropertyInfo>> RecrusiveReflectionCompare<T>(T first, T second) | |
where T : class | |
{ | |
var differences = new List<KeyValuePair<Type, PropertyInfo>>(); | |
var parentType = first.GetType(); | |
void CompareObject(object obj1, object obj2, PropertyInfo info) | |
{ | |
if (!obj1.Equals(obj2)) | |
{ | |
differences.Add(new KeyValuePair<Type, PropertyInfo>(parentType, info)); | |
} | |
} | |
foreach (PropertyInfo property in parentType.GetProperties()) | |
{ | |
object value1 = property.GetValue(first, null); | |
object value2 = property.GetValue(second, null); | |
if (property.PropertyType == typeof(string)) | |
{ | |
if (string.IsNullOrEmpty(value1 as string) != string.IsNullOrEmpty(value2 as string)) | |
{ | |
CompareObject(value1, value2, property); | |
} | |
} | |
else if (property.PropertyType.IsPrimitive) | |
{ | |
CompareObject(value1, value2, property); | |
} | |
else | |
{ | |
if (value1 == null && value2 == null) | |
{ | |
continue; | |
} | |
differences.Concat(RecrusiveReflectionCompare(value1, value2)); | |
} | |
} | |
return differences; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment