I have two objects of the same type, and I want to loop through the public properties on each of them and alert the user about which properties don't match.
Is it possible to do this without knowing what properties the object contains?
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables). Objects are identical when they share the class identity.
The == operator compares whether two object references point to the same object.
The Equals method and the IEquatable<T> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects. You could use reflection by comparing each property values.
Yes, with reflection - assuming each property type implements Equals
appropriately. An alternative would be to use ReflectiveEquals
recursively for all but some known types, but that gets tricky.
public bool ReflectiveEquals(object first, object second)
{
if (first == null && second == null)
{
return true;
}
if (first == null || second == null)
{
return false;
}
Type firstType = first.GetType();
if (second.GetType() != firstType)
{
return false; // Or throw an exception
}
// This will only use public properties. Is that enough?
foreach (PropertyInfo propertyInfo in firstType.GetProperties())
{
if (propertyInfo.CanRead)
{
object firstValue = propertyInfo.GetValue(first, null);
object secondValue = propertyInfo.GetValue(second, null);
if (!object.Equals(firstValue, secondValue))
{
return false;
}
}
}
return true;
}
Sure you can with reflection. Here is the code to grab the properties off of a given type.
var info = typeof(SomeType).GetProperties();
If you can give more info on what you're comparing about the properties we can get together a basic diffing algorithmn. This code for intstance will diff on names
public bool AreDifferent(Type t1, Type t2) {
var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
return list1.SequenceEqual(list2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With