How to compare properties between two objects

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 the same value.

  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 the value of all properties in two classes by reflection. My ultimate goal is the value of the difference of these 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 the result is not satisfactory. The diffProperties graph for the result was 4 , but the number of expectations was 1 .

Of course, all properties can have null values.

I need a general solution. What should I do?

+6
source share
4 answers

If you want to stick to comparisons through reflection, you shouldn't use! = (Reference equality, which will cause most comparisons to fail for the boxed results of GetProperty calls), but use a static Object instead . Equal Method .

An example of using the Equals method to compare two objects in your reflection code.

  if (!Object.Equals( item.GetValue(person, null), dto.GetType().GetProperty(item.Name).GetValue(dto, null))) { diffProperties.Add(item); } 
+11
source

You can consider the Person class that implements the IComparable interface and implement the CompareTo (Object obj) method.

+1
source
0
source

Looking at you, classes may not all be null; you have a nullable long. But that is said.

I also did something similar and used this site . Just make it so that it can take 2 different objects. I cannot share my code due to licensing.

-1
source

Source: https://habr.com/ru/post/923451/


All Articles