Compare Properties automatically
        Posted  
        
            by 
                juergen d
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by juergen d
        
        
        
        Published on 2013-06-17T20:06:34Z
        Indexed on 
            2013/06/26
            22:22 UTC
        
        
        Read the original article
        Hit count: 277
        
I want to get the names of all properties that changed for matching objects. I have these (simplified) classes:
public enum PersonType { Student, Professor, Employee }
class Person {
    public string Name { get; set; }
    public PersonType Type { get; set; }
}
class Student : Person {
     public string MatriculationNumber { get; set; }
}
class Subject {
     public string Name { get; set; }
     public int WeeklyHours { get; set; }
}
class Professor : Person {
    public List<Subject> Subjects { get; set; }
}
Now I want to get the objects where the Property values differ:
List<Person> oldPersonList = ...
List<Person> newPersonList = ...
List<Difference> = GetDifferences(oldPersonList, newPersonList);
public List<Difference> GetDifferences(List<Person> oldP, List<Person> newP) {
     //how to check the properties without casting and checking 
     //for each type and individual property??
     //can this be done with Reflection even in Lists??
}
In the end I would like to have a list of Differences like this:
class Difference {
    public List<string> ChangedProperties { get; set; }
    public Person NewPerson { get; set; }
    public Person OldPerson { get; set; }
}
The ChangedProperties should contain the name of the changed properties.
© Stack Overflow or respective owner