Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare properties between two objects

Tags:

c#

reflection

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 4but count of my expect was 1.

Of course all properties can have null values.

I need to a solution generic. What must do I?

like image 245
Ehsan Avatar asked Aug 22 '12 06:08

Ehsan


2 Answers

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);
 } 
like image 129
M.Azad Avatar answered Sep 30 '22 11:09

M.Azad


You may consider making the Person class implement the IComparable interface and implementing the CompareTo(Object obj) method.

like image 33
Kishore Borra Avatar answered Sep 30 '22 11:09

Kishore Borra