Skip to content

Instantly share code, notes, and snippets.

@jakcharlton
Created June 15, 2011 06:17
Show Gist options
  • Save jakcharlton/1026582 to your computer and use it in GitHub Desktop.
Save jakcharlton/1026582 to your computer and use it in GitHub Desktop.
Property equality comparison on two objects
// Shamelessly stolen and adapted from http://stackoverflow.com/questions/506096/comparing-object-properties-in-c
public static class Comparisons
{
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);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
if (ignoreList.Contains(pi.Name)) continue;
var selfValue = type.GetProperty(pi.Name).GetValue(self, null);
var toValue = type.GetProperty(pi.Name).GetValue(to, null);
if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
return false;
}
return true;
}
return self == to;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment