Property Based Object Comparer
Today i need to get two different type of objects compared by their property values.
Problem was those objects are not supporting IComparable interface. Yet they might be different type of objects. Basicly they are plain objects, POJO’s. Google’ed to find a class that compares two objects by looking their property values but couldn’t find any simple implementation.
So I had to code it right away and I wanted to share.
namespace Sample.Data
{
public class PropertyBasedComparer
{
public bool AreEqual(Object obj1, Object obj2)
{
if (obj1 == null) throw new ArgumentNullException();
if (obj2 == null) throw new ArgumentNullException();
PropertyInfo[] properties = obj1.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
if (obj2.GetType().GetProperty(p.Name)==null)
continue;
if (p.PropertyType.IsValueType)
{
if (p.GetValue(obj1, null) != p.GetValue(obj2, null))
return false;
continue;
}
if (p.PropertyType == typeof(string))
{
if (!p.GetValue(obj1, null).ToString().Equals(p.GetValue(obj2, null).ToString()))
return false;
}
}
return true;
}
}
}