Given two objected that do not contain reference loops within them, do you know a method that tests their equality in a "generic" way (through reflection)?
I basically want the same semantics as struct equivalence, only on classes.
Given two objected that do not contain reference loops within them, do you know a method that tests their equality in a "generic" way (through reflection)?
I basically want the same semantics as struct equivalence, only on classes.
I think there is no such method available in the framework, but it's fairly easily written. Perhaps not the shortest implementation but is seems to do the job:
private bool AreEqual(object x, object y)
{
// if both are null, they are equal
if (x == null && y == null)
{
return true;
}
// if one of them are null, they are not equal
else if (x == null || y == null)
{
return false;
}
// if they are of different types, they can't be compared
if (x.GetType() != y.GetType())
{
throw new InvalidOperationException("x and y must be of the same type");
}
Type type = x.GetType();
PropertyInfo[] properties = type.GetProperties();
for (int i = 0; i < properties.Length; i++)
{
// compare only properties that requires no parameters
if (properties[i].GetGetMethod().GetParameters().Length == 0)
{
object xValue = properties[i].GetValue(x, null);
object yValue = properties[i].GetValue(y, null);
if (properties[i].PropertyType.IsValueType && !xValue.Equals(yValue))
{
return false;
}
else if (!properties[i].PropertyType.IsValueType)
{
if (!AreEqual(xValue, yValue))
{
return false;
}
} // if
} // if
} // for
return true;
}
If you want to do this without doing reflection on each call, you might want to consider building a DynamicMethod
on first invocation and using that instead. (I had a link to the article that does this, but I lost it - sorry - try Googling if interested.)
BTW
Expression.Lambda<Func<T,T,bool>> Compile()
can be used as a dynamic method builder.
still have to use reflection while building the Expresison