I have two similar classes : Person
, PersonDto
public class Person
{
public string Name { get; set; }
public long Serial { get; set; }
public DateTime Date1 { get; set; }
public DateTime? Date2 { get; set; }
}
&
public class PersonDto
{
public string Name { get; set; }
public long Serial { get; set; }
public DateTime Date1 { get; set; }
public DateTime? Date2 { get; set; }
}
I have two objects of both by equal values.
var person = new Person { Name = null , Serial = 123, Date1 = DateTime.Now.Date, Date2 = DateTime.Now.Date };
var dto = new PersonDto { Name = "AAA", Serial = 123, Date1 = DateTime.Now.Date, Date2 = DateTime.Now.Date };
I need to check value of all properties in two classes by reflection. My final goal is defined difference value of this properties.
IList diffProperties = new ArrayList();
foreach (var item in person.GetType().GetProperties())
{
if (item.GetValue(person, null) != dto.GetType().GetProperty(item.Name).GetValue(dto, null))
diffProperties.Add(item);
}
I did this, but result is not satisfactory. Count of diffProperties
for result was 4
but count of my expect was 1
.
Of course all properties can have null values.
I need to a solution generic. What must do I?
If you want to stick with comparison via reflection you should not use != (reference equality which will fail most of comparisons for boxed results of GetProperty calls) but instead use static Object.Equals method.
Sample how to use Equals method to compare two object in your reflection code.
if (!Object.Equals(
item.GetValue(person, null),
dto.GetType().GetProperty(item.Name).GetValue(dto, null)))
{
diffProperties.Add(item);
}
You may consider making the Person
class implement the IComparable
interface and implementing the CompareTo(Object obj)
method.
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