I need to define a method to compare two different objects of a same type. The type of objects is not specific. The objects may be a DLL type, so I can’t override Equals method. I have to do this by reflection. This code works if all the members of objects are of primitive type. But it doesn’t work when an object has a field that isn’t primitive. How can I do it by reflection?
public bool Equals(object obj1, object obj2)
{
List<FieldInfo> fieldInfos = obj1.GetType().GetFields().ToList();
return (fieldInfos.Select(fieldInfo => new {fieldInfo, type = fieldInfo.GetType()})
.Where(@t => @t.type.IsPrimitive || @t.type == typeof(string) || @t.type == typeof(Decimal))
.Select(@t => @t.fieldInfo)).All(fieldInfo => fieldInfo.GetValue(obj1).Equals(fieldInfo.GetValue(obj2)));
}
I have recently been told about this lib that will do exactly what you are wanting
http://comparenetobjects.codeplex.com/releases/view/47978